Here is the code:
....
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");
//开发者_Go百科 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);
}
....
I have put my question in the code, i.e question i - vi
My feeling telling me, my arguments are wrong, for example the question vi:
pthread_cond_init(notEmpty,NULL);
it should be something else, not "(¬Empty,Null)".
Please help.
notNull
is written as notFull
in two places.
notNull
and notEmpty
are condition variables not mutexes and should be initialised as such.
No memory is allocated for notNull
and notEmpty
.
It may be better to declare queue
as:
typedef struct {
int buf[10];
long head, tail;
int full, empty;
pthread_mutex_t mut;
pthread_cond_t notFull;
pthread_cond_t notEmpty;
} queue;
And then keep all the &
characters. This means you can malloc the whole lot with a single call.
Lastly I think you mean while(que->full)
not while(que>full)
.
you should not use &
when you already have a pointer. Change this:
// 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
to this:
// 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
Pay attention to &
I have put away. mut
is already a pointer, and making &mut
is an attempt to get pointer to pointer to pthread_mutex_t
精彩评论