2010-12-07 99 views
1

下面是代码: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(&notFull, &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(&notEmpty); // 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(&notNull,NULL); // Question vi 
    // Condition for not empty 
    pthread_mutex_init(&notEmpty,NULL); // Question vi 
    return (q); 
} 
.... 

我已经把我的问题中的代码,即问题我 - 六

我的感觉告诉我,我的论点是错误的,例如问题六:

pthread_cond_init(notEmpty,NULL); 

它应该是别的东西,而不是“(& notEmpty,Null)”。

请帮忙。

+0

两个条件变量看起来很丑,通常意味着它不是一个理想的解决方案。你可以只有一个条件变量“queueChanged”或其他东西,并标记当队列获得或失去一个项目。 – AlastairG 2010-12-07 14:57:51

回答

1

如果您已经有指针,则不应使用&。更改此:

// Set default condition 
    pthread_mutex_init(&mut,NULL); // Question v 
    // Condition for not null 
    pthread_mutex_init(&notNull,NULL); // Question vi 
    // Condition for not empty 
    pthread_mutex_init(&notEmpty,NULL); // Question vi 

这样:

// Set default condition 
    pthread_mutex_init(mut,NULL); // Question v 
    // Condition for not null 
    pthread_mutex_init(notNull,NULL); // Question vi 
    // Condition for not empty 
    pthread_mutex_init(notEmpty,NULL); // Question vi 

注重&我已经放好。 mut已经是一个指针,使得&mut是企图让指针指向pthread_mutex_t

+0

谢谢。这个问题怎么样?任何想法? – cecillia90 2010-12-07 14:17:07

2

notNull是在两个地方写为notFullnotNullnotEmpty是不是互斥锁的条件变量,应该像这样初始化。 没有内存分配给notNullnotEmpty

这可能是更好的声明queue为:

typedef struct { 
    int buf[10]; 
    long head, tail; 
    int full, empty; 
    pthread_mutex_t mut; 
    pthread_cond_t notFull; 
    pthread_cond_t notEmpty; 
} queue; 

然后把所有的&字符。这意味着您可以通过一次调用就可以完成全部工作。

最后,我认为你的意思是while(que->full)而不是while(que>full)