/***************************************************
*--------------------------------------------------
* Creat : 2001. 02. 10 (programed by Cori-Young )
* Site: http://www.byoneself.co.kr
* Update :
*--------------------------------------------------
* Compile : cc -o conpro conpro.c -lpthread -lrt
*--------------------------------------------------
* Machine hardware: sun4u
* OS version: 5.7
* Processor type: sparc
* Hardware: SUNW,Ultra-60
***************************************************/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t produced, consumed; /* semaphores */
int n;
main()
{
pthread_t idprod, idcons; /* ids of threads */
void *produce(void *);
void *consume(void *);
int loopcnt = 5;
n = 0;
if (sem_init(&consumed, 0, 0) < 0)
{
perror("sem_init");
exit(1);
}
if (sem_init(&produced, 0, 1) < 0)
{
perror("sem_init");
exit(1);
}
if (pthread_create(&idprod, NULL, produce, (void *)loopcnt) != 0)
{
perror("pthread_create");
exit(1);
}
if (pthread_create(&idcons, NULL, consume, (void *)loopcnt) != 0)
{
perror("pthread_create");
exit(1);
}
(void)pthread_join(idprod, NULL);
(void)pthread_join(idcons, NULL);
(void)sem_destroy(&produced);
(void)sem_destroy(&consumed);
}
void *produce(void *arg)
{
int i, loopcnt;
loopcnt = (int)arg;
for (i=0; i<loopcnt; i++)
{
sem_wait(&consumed);
n++; /* increment n by 1 */
sleep(1);
sem_post(&produced);
}
}
void *consume(void *arg)
{
int i, loopcnt;
loopcnt = (int)arg;
for (i=0; i<loopcnt; i++)
{
sem_wait(&produced);
printf("n is %dn", n); /* print value of n */
sem_post(&consumed);
}
} |
|