X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=prodcons%2Fprodcons.c;fp=prodcons%2Fprodcons.c;h=a533b48ad247254baf5eeb296dc55c1f5f3564de;hb=66c9107fcb99df4eec36a84db41f78eb946cc224;hp=0000000000000000000000000000000000000000;hpb=35dc22ea52cbc9941103bf4b20ea9102d70d9534;p=TD_SE.git diff --git a/prodcons/prodcons.c b/prodcons/prodcons.c new file mode 100644 index 0000000..a533b48 --- /dev/null +++ b/prodcons/prodcons.c @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include + +#define MAX 6 +#define BUF_SIZE 3 +typedef struct args { + sem_t sem_free; + sem_t sem_busy; +} args_t; +static int buf[BUF_SIZE]; +void *prod(void *arg); +void *cons(void *arg); + +int main() +{ + pthread_t t1, t2; + args_t args; + sem_init(&args.sem_free, 0, BUF_SIZE); + sem_init(&args.sem_busy, 0, 0); + pthread_create(&t1, NULL, prod, &args); + pthread_create(&t2, NULL, cons, &args); + pthread_join(t1, NULL); + pthread_join(t2, NULL); + printf("exit\n"); + return EXIT_SUCCESS; +} + +void *prod(void *arg) +{ + int ip = 0, nbprod = 0, obj = 1001; + args_t *args = (args_t *) arg; + while (nbprod < MAX) { + sem_wait(&args->sem_free); + buf[ip] = obj; + sem_post(&args->sem_busy); + printf("prod: buf[%d]=%d\n", ip, obj); + obj++; + nbprod++; + ip = (ip + 1) % BUF_SIZE; + } + return NULL; +} + +void *cons(void *arg) +{ + int ic = 0, nbcons = 0, obj; + args_t *args = (args_t *) arg; + while (nbcons < MAX) { + sleep(1); + sem_wait(&args->sem_busy); + obj = buf[ic]; + sem_post(&args->sem_free); + printf("cons: buf[%d]=%d\n", ic, obj); + nbcons++; + ic = (ic + 1) % BUF_SIZE; + } + return NULL; +}