linux中的线程同步:生产者、消费者问题

2023-06-05,,

#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_COUNT 5 int Buffer[BUFFER_COUNT]; //指针数组
int front = ;
int tail = ; sem_t SemProd;
sem_t SemCon; void* productor(void *arg)
{
int counter = ;
while()
{
int ret = sem_wait(&SemProd);
sleep(); //模拟输入处理时延
Buffer[tail] = counter; printf("in productor: %d, %d\n", counter++, ret);
tail = (tail + ) % BUFFER_COUNT; //
sem_post(&SemCon);
}
return NULL;
} void* consumer(void *arg)
{
while()
{
sem_wait(&SemCon);
sleep(); //模拟输出处理时延
printf("in consumer: %d, %d\n", Buffer[front], front);
front = (front + ) % BUFFER_COUNT;
sem_post(&SemProd);
}
} int main(int argv, char **argc)
{
pthread_t id1, id2;
sem_init(&SemProd, , BUFFER_COUNT);
sem_init(&SemCon, , ); pthread_create(&id1, NULL, productor, NULL);
pthread_create(&id2, NULL, consumer, NULL); pthread_join(id1, NULL);
pthread_join(id2, NULL);
}

linux中的线程同步生产者、消费者问题的相关教程结束。

《linux中的线程同步:生产者、消费者问题.doc》

下载本文的Word格式文档,以方便收藏与打印。