pthreads problem

Gerhard Hoffmann gh1001 at rbg.informatik.tu-darmstadt.de
Sun Aug 7 09:04:04 GMT 2005


Hi Phil,

I think the easiest solution for your problem is something like this:

#include <stdio.h>
#include <pthread.h>

volatile unsigned long len   = 0;
pthread_mutex_t lock       = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond       = PTHREAD_COND_INITIALIZER;

static void cleanup_handler(void *arg) {
  (void)pthread_mutex_unlock(&lock);
  (void)pthread_mutex_destroy(&lock);
  (void)pthread_cond_destroy(&cond);
}

static void *thread_routine(void *args) {

        pthread_cleanup_push(cleanup_handler,(void*)NULL);

        while (1) {
               
                pthread_mutex_lock(&lock);

                while(len == 0)
                        pthread_cond_wait(&cond, &lock);
   
                fprintf(stderr,"consumer: %lu\n", --len);

                pthread_cond_signal(&cond);
                pthread_mutex_unlock(&lock);
       }
     
       pthread_cleanup_pop(0);

       return NULL;
}

int main(int argc, char **argv) {
 
        pthread_t t;
        int i;
 
        pthread_create(&t, NULL, &thread_routine, NULL);
 
        for (i = 0; i < 100; i++) {
   
                pthread_mutex_lock(&lock);
               
                while(len > 5)
                        pthread_cond_wait(&cond, &lock);
   
                fprintf(stderr,"producer: %lu\n", ++len);
               
                pthread_cond_signal(&cond);
                pthread_mutex_unlock(&lock);
        }
 
        pthread_cancel(t); 
        pthread_join(t, NULL);

        return 0;
}


Gerhard




More information about the freebsd-hackers mailing list