From: 001 on 12 Nov 2009 08:55 I tried to make a producer of 'items' but my implementation crashes at pthread_cond_wait ... I really tried looking at everything and put print statements throughout my code, but there it just crashes. I did put the wait within a mutex. This code isn't complete, but the relevant parts are in there (I assume). Any idea what I did wrong? This is the first time I used condition variables. Oh yeah... another question: is it possible to wait on multiple condition variables (and continue when one of them changes)? So that I can stop a thread independent of whether or not it is waiting for something? Sincerely, Stéphane Thibaud #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <pthread.h> // needed for pthreads #include <unistd.h> // for usleep() #include "prodcons.h" static unsigned int prodCount = 0; // The number of produces items static unsigned int bufferHead = 0; // Indicates the first free place in buffer or undefined when prodCount = BUFFER_SIZE static unsigned int inBufferCnt = 0; // Number of items in buffer static pthread_mutex_t bufferLock; static pthread_cond_t bufferNotFull; static pthread_cond_t availForCons[NROF_CONSUMERS]; // Conditions variables for the availability of items on the belt (per consumer) static const unsigned short int ALL_ONES = 0xFFFF; static int producing = 1; static void rsleep (int t); static void * producer (/*void * arg*/) { ITEM item; // a produced item while (prodCount < NROF_ITEMS) // While not all items are produced { rsleep (PRODUCER_SLEEP_FACTOR); item = (random() % NROF_CONSUMERS) + (prodCount << NROF_BITS_DEST); prodCount++; pthread_mutex_lock(&bufferLock); printf("justlocked\n"); if(inBufferCnt == BUFFER_SIZE) { printf("full buffer\n"); pthread_cond_wait(&bufferNotFull, &bufferLock); printf("not full anymore\n"); } buffer[bufferHead] = item; bufferHead = (bufferHead + 1) % BUFFER_SIZE; inBufferCnt++; if(inBufferCnt == 1) { printf("consumer signaled\n"); pthread_cond_signal(&availForCons[buffer [bufferHead - 1] & ~ (ALL_ONES << NROF_BITS_DEST)]); } printf("%04x\n", item); // write info to stdout, putting it inside the CS ensures no two threads write to stdout at the same time printf("unlockingnext\n"); pthread_mutex_unlock(&bufferLock); } producing = 0; return NULL; }
From: Ian Collins on 12 Nov 2009 16:55 001 wrote: Please don't multi-post! -- Ian Collins
|
Pages: 1 Prev: How to perform a sort based on my own comparison? Next: Accelerated C++ Problem setw |