Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 07 Aug 2005 11:03:24 +0200
From:      Gerhard Hoffmann <gh1001@rbg.informatik.tu-darmstadt.de>
To:        freebsd-hackers@freebsd.org
Subject:   pthreads problem
Message-ID:  <42F5CE5C.9060602@rbg.informatik.tu-darmstadt.de>

next in thread | raw e-mail | index | archive | help
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





Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?42F5CE5C.9060602>