#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#define MAX_PRODUCT 32
typedef struct PRODUCT_S {
int p_idx; /* Producer's index*/
int c_idx; /* Consumer's index*/
Short Init; /* Initialize flag */
Char Data[max_product]; /* for saving products */
pthread_mutex_t Mutex; /* Mutex lock */
sem_t sem; /* Semaphore Volume */
} product;
Producer Thread Entry function
void *producer_thread (void *arg)
{
Product *p = (product *) arg;
for (;;) {
Pthread_mutex_lock (&p->mutex);
Srand (Time (NULL));
char C = rand ()% 26 + 65; Randomly produces a character
if (P->p_idx > 31) {//over 31, re-overwrite from 0
P->p_idx = p->p_idx% Max_product;
}
P->DATA[P->P_IDX] = c;
printf ("Create%c, idx%d\n", C, P->p_idx);
p->p_idx++;
Pthread_mutex_unlock (&p->mutex);
Sem_post (&p->sem);
Sleep (1);
}
return (void *) 0;
}
Consumer Thread Entry function
void *consumer_thread (void *arg)
{
Product *p = (product *) arg;
for (;;) {
Sem_wait (&p->sem);
Pthread_mutex_lock (&p->mutex);
if (P->c_idx > 31) {
P->c_idx = p->c_idx% Max_product;
}
printf ("Get%c, idx%d\n", P->data[p->c_idx], p->c_idx);
p->c_idx++;
Pthread_mutex_unlock (&p->mutex);
}
return (void *) 0;
}
int main ()
{
Product p;
memset (&p, 0, sizeof (p));
if (Sem_init (&p.sem, 0, 0)! = 0) {
fprintf (stderr, "Sem_init error\n");
Exit (1);
}
if (Pthread_mutex_init (&p.mutex, NULL)! = 0) {
fprintf (stderr, "Pthread_mutex_init error\n");
Exit (1);
}
pthread_attr_t attr;
if (Pthread_attr_init (&attr)! = 0) {
fprintf (stderr, "Pthread_attr_init error\n");
Exit (1);
}
if (Pthread_attr_setdetachstate (&attr, pthread_create_detached)! = 0) {
fprintf (stderr, "Pthread_attr_setdetachstate error\n");
Exit (1);
}
pthread_t Tid;
if (Pthread_create (&tid, &attr, Consumer_thread, (void *) &p)! = 0) {
fprintf (stderr, "Pthread_create error\n");
Exit (1);
}
if (Pthread_create (&tid, &attr, Producer_thread, (void *) &p)! = 0) {
fprintf (stderr, "Pthread_create error\n");
Exit (1);
}
Pause ();
Sem_destroy (&p.sem);
Pthread_attr_destroy (&ATTR);
return 0;
}
Makefile File:
Read:read.c
Gcc-o [email protected] $^-lpthread
. Phony:clean
Clean
Rm-f Read
650) this.width=650; "title=" QQ picture 20160719104139.png "Src=" http://s5.51cto.com/wyfs02/M01/84/54/wKioL1eNk-nQ5cA_ Aaayshvlkv0404.png "alt=" Wkiol1enk-nq5ca_aaayshvlkv0404.png "/>
Multi-producer multi-consumer synchronization and mutual exclusion based on POSIX version semaphore