下面是代码:C线程互斥代码错误?
....
typedef struct {
int buf[10];
long head, tail;
int full, empty;
pthread_mutex_t *mut;
pthread_cond_t *notFull, *notEmpty;
} queue;
int main(){
queue *que;
pthread_t sup, cut;
que = queueInit();
if(que == NULL){
fprintf(stderr, "Queue Init failed");
exit(1);
}
pthread_create(&sup, NULL, insertQueue, (void*) que);
pthread_create(&cut, NULL, insertQueue, (void*) que);
pthread_join(sup,NULL);
pthread_join(cut,NULL);
queueDelete(que);
return 0;
}
void *insertQueue(void *q)
{
queue *que;
int i;
que = (queue *)q;
for(i=0; i<20;i++){
// Get mutex lock on the queue
pthread_mutex_lock(&mut); // Question (i) I guess this line is wrong
while(que>full){
printf("Its full");
// pthread wait condition for queue not full
pthread_cond_wait(¬Full, &mut); // Question (ii)
}
queueAdd(que,i);
// Unlock the queue
pthread_mutex_unlock(&mut); // Question (iii)
// Send signal saying there is data to be read
pthread_cond_signal(¬Empty); // Question (iv)
usleeep(100000);)
return(NULL);
}
}
queue *queueInit(void){
queue *q;
q = (queue *)malloc(sizeof(queue));
if(q==NULL) return (NULL);
q->empty = 1;
q->full = 0;
q->head = 0;
q->tail = 0;
q->mut=(pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
// Set default condition
pthread_mutex_init(&mut,NULL); // Question v
// Condition for not null
pthread_mutex_init(¬Null,NULL); // Question vi
// Condition for not empty
pthread_mutex_init(¬Empty,NULL); // Question vi
return (q);
}
....
我已经把我的问题中的代码,即问题我 - 六
我的感觉告诉我,我的论点是错误的,例如问题六:
pthread_cond_init(notEmpty,NULL);
它应该是别的东西,而不是“(& notEmpty,Null)”。
请帮忙。
两个条件变量看起来很丑,通常意味着它不是一个理想的解决方案。你可以只有一个条件变量“queueChanged”或其他东西,并标记当队列获得或失去一个项目。 – AlastairG 2010-12-07 14:57:51