码迷,mamicode.com
首页 > 其他好文 > 详细

多生产者多消费者基于POSIX版本信号量的同步与互斥

时间:2016-07-19 13:58:58      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:多生产者多消费者基于posix版本信号量的同步与互斥

#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

技术分享

多生产者多消费者基于POSIX版本信号量的同步与互斥

标签:多生产者多消费者基于posix版本信号量的同步与互斥

原文地址:http://frankenstein.blog.51cto.com/10918184/1827672

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!