#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;             /*生产者的index*/
  int             c_idx;             /*消费者的index*/
  short           init;              /*初始化标志*/
  char            data[MAX_PRODUCT]; /*用于保存产品*/
  pthread_mutex_t mutex;             /*互斥锁*/
  sem_t           sem;               /*信号量*/
} product;

//生产者线程入口函数
void *producer_thread(void *arg)
{
 product *p = (product *)arg;
 for ( ;; ) {
  pthread_mutex_lock(&p->mutex);
  srand(time(NULL));
  char c = rand() % 26 + 65; //随机产生一个字符
  if (p->p_idx > 31) { //超过31, 重新从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;
}

//消费者线程入口函数
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文件:

read:read.c
 gcc -o $@ $^ -lpthread
.PHONY:clean
clean:
 rm -f read

wKioL1eNk-nQ5cA_AAAysHVLkv0404.png