asp网站程序优点,正定城乡建设网站,哪个网站教做ppt模板,陕西网站建设价格请使用条件变量实现2生产者2消费者模型#xff0c;注意1个生产者在生产的时候#xff0c;另外一个生产者不能生产。
1程序代码
#include stdio.h
#include string.h
#include unistd.h
#include stdlib.h
#include sys/types.h注意1个生产者在生产的时候另外一个生产者不能生产。
1程序代码
#include stdio.h
#include string.h
#include unistd.h
#include stdlib.h
#include sys/types.h
#include sys/stat.h
#include fcntl.h
#include pthread.h
#include semaphore.h
#include wait.h
#include signal.h
#include sys/socket.h
#include arpa/inet.h
#include sys/socket.h
#include sys/ipc.h
#include sys/sem.h
#include semaphore.h
#include sys/msg.h
#include sys/shm.h
#include sys/un.htypedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;#define BUFFER_SIZE 5
#define PRODUCER_COUNT 2
#define CONSUMER_COUNT 2// 缓冲区
int buffer[BUFFER_SIZE];
// 缓冲区索引
int in 0;
int out 0;
// 缓冲区中的元素数量
int count 0;// 互斥锁和条件变量
pthread_mutex_t mutex;
pthread_cond_t not_full;
pthread_cond_t not_empty;// 生产者互斥锁
pthread_mutex_t producer_mutex;// 生产者线程函数
void *producer(void *arg) {int id *(int *)arg;while (1) {// 加锁确保同一时间只有一个生产者可以生产pthread_mutex_lock(producer_mutex);// 加锁保护共享资源pthread_mutex_lock(mutex);// 等待缓冲区有空闲位置while (count BUFFER_SIZE) {pthread_cond_wait(not_full, mutex);}// 生产一个数据buffer[in] rand() % 100;printf(Producer %d produced %d at position %d\n, id, buffer[in], in);in (in 1) % BUFFER_SIZE;count;// 通知消费者缓冲区有数据了pthread_cond_signal(not_empty);// 解锁pthread_mutex_unlock(mutex);// 解锁生产者互斥锁pthread_mutex_unlock(producer_mutex);// 模拟生产时间sleep(1);}return NULL;
}// 消费者线程函数
void *consumer(void *arg) {int id *(int *)arg;while (1) {// 加锁保护共享资源pthread_mutex_lock(mutex);// 等待缓冲区有数据while (count 0) {pthread_cond_wait(not_empty, mutex);}// 消费一个数据int item buffer[out];printf(Consumer %d consumed %d from position %d\n, id, item, out);out (out 1) % BUFFER_SIZE;count--;// 通知生产者缓冲区有空闲位置了pthread_cond_signal(not_full);// 解锁pthread_mutex_unlock(mutex);// 模拟消费时间sleep(1);}return NULL;
}int main(int argc, const char *argv[])
{// 初始化互斥锁和条件变量pthread_mutex_init(mutex, NULL);pthread_cond_init(not_full, NULL);pthread_cond_init(not_empty, NULL);pthread_mutex_init(producer_mutex, NULL);// 创建生产者和消费者线程pthread_t producers[PRODUCER_COUNT];pthread_t consumers[CONSUMER_COUNT];int producer_ids[PRODUCER_COUNT];int consumer_ids[CONSUMER_COUNT];for (int i 0; i PRODUCER_COUNT; i) {producer_ids[i] i;pthread_create(producers[i], NULL, producer, producer_ids[i]);}for (int i 0; i CONSUMER_COUNT; i) {consumer_ids[i] i;pthread_create(consumers[i], NULL, consumer, consumer_ids[i]);}// 等待线程结束for (int i 0; i PRODUCER_COUNT; i) {pthread_join(producers[i], NULL);}for (int i 0; i CONSUMER_COUNT; i) {pthread_join(consumers[i], NULL);}// 销毁互斥锁和条件变量pthread_mutex_destroy(mutex);pthread_cond_destroy(not_full);pthread_cond_destroy(not_empty);pthread_mutex_destroy(producer_mutex);return 0;
}2运行效果