DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Threads

Producer/consumer

#include        <stdio.h>
#include        <stdlib.h>
#include        <string.h>
#include        <thread.h>
#include        <synch.h>
#define TRUE    1
#define FALSE   0
static  void    *producer(void*);
static  void    *consumer(void*);
static  char    Buff[BUFSIZ];
static  cond_t  Buff_cond;
static  mutex_t Buff_mutex;
static  int     DataInBuff = FALSE;
main()
{
        (void)mutex_init(&Buff_mutex, USYNC_THREAD,  NULL);
        (void)cond_init (&Buff_cond,  USYNC_THREAD,  NULL);
        (void)thr_create(NULL, 0, producer, NULL, 0, NULL);
        (void)thr_create(NULL, 0, consumer, NULL, 0, NULL);
        thr_exit(NULL);
        /*NOTREACHED*/
}
/*ARGSUSED*/
static void *producer(void *dummy)
{
	(void)mutex_lock(&Buff_mutex);
        for(;;){
                while(DataInBuff == TRUE)
                        cond_wait(&Buff_cond, &Buff_mutex);
		/* At this point,
		 * the buffer is empty (contents have been output).
		 * (Re)fill the buffer.
		 */
                if(fgets(Buff, sizeof(Buff), stdin) == NULL)
                        exit(EXIT_SUCCESS);
                DataInBuff = TRUE;
                cond_signal (&Buff_cond);
        }
        /*NOTREACHED*/
}
/*ARGSUSED*/
static void *consumer(void *dummy)
{
        (void)mutex_lock(&Buff_mutex);
        for(;;){
                while(DataInBuff == FALSE)
                        cond_wait(&Buff_cond, &Buff_mutex);
		/* At this point,
		 * the buffer has data to be output
		 */
                (void)fputs(Buff, stdout);
                DataInBuff = FALSE;
                cond_signal(&Buff_cond);
        }
        /*NOTREACHED*/
}

Producer/consumer

The program in ``Producer/consumer'' shows a simple producer/consumer example implemented using the condition variables facilities of the Threads Library.


Previous topic: Dining philosophers

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004