- 论坛徽章:
- 0
|
一个简单的生产者,消费者问题,请问为何在注释掉消费者和生产者线程中sleep()函数,就会出现段错误啊~我是CU新手,大家帮忙看一下,非常感谢~~!代码如下:
#include <stdio.h>
#include <pthread.h>
#include <malloc.h>
#include <time.h>
#include <error.h>
#define MAX_SIZE 40
typedef struct list{
int i;
struct list *next;
}list;
pthread_t tid;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t no_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t no_full = PTHREAD_COND_INITIALIZER;
static list list_head = {
.i = 0,
.next = NULL,
};
static void *produce(){
time_t t;
srand((unsigned)time(&t));
for(; {
list *node;
node = (list *)malloc(sizeof(list));
node->i = (int)rand();
node->next = NULL;
// sleep(1);
pthread_mutex_lock(&lock);
if(list_head.i == MAX_SIZE)
pthread_cond_wait(&no_full, &lock);
list_head.next = node;
list_head.i += 1;
printf("I Produce val=%d\n", node->i);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&no_empty);
}
}
static void *consume(){
list *tmp;
for(; {
// sleep(1);
pthread_mutex_lock(&lock);
if(list_head.i == 0)
pthread_cond_wait(&no_empty, &lock);
tmp = list_head.next;
printf("I Consume val=%d\n",tmp->i);
list_head.next = tmp->next;
free(tmp);
tmp = NULL;
list_head.i -= 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&no_full);
}
}
int main(){
pthread_t pro_tid;
pthread_t con_tid;
void *pret;
void *cret;
if(pthread_create(&pro_tid, NULL, produce, NULL) != 0){
perror("pthread_create_pro_error:" ;
}
if(pthread_create(&con_tid, NULL, consume, NULL) != 0){
perror("pthread_create_con_error:" ;
}
if(pthread_join(pro_tid, &pret) != 0){
perror("join_pro_error:" ;
}
if(pthread_join(con_tid, &cret) != 0){
perror("join_pro_error:" ;
}
return 0;
} |
|