【发布时间】:2021-11-04 14:38:44
【问题描述】:
伙计们。我正在学习生产者-消费者问题。我的教授给了我们一个示例代码,使用经典的int array 在两个线程之间共享资源。它按预期工作,但是,我想使用 C++ 中的std:list 类尝试它,但它没有按预期工作。消费者似乎不尊重sem_wait(&full);,所以当共享列表中没有任何内容时,它会尝试多次消费。
带有数组缓冲区的原始代码
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define N 2
#define TRUE 1
int buffer[N], in = 0, out = 0;
sem_t empty, full, mutexC, mutexP;
void *producer(void *arg) {
while(TRUE) {
sleep(rand()%5);
sem_wait(&empty);
sem_wait(&mutexP);
buffer[in] = rand() % 100;
printf("Producing buffer[%d] = %d\n", in, buffer[in]);
in= (in+1) % N;
sem_post(&mutexP);
sem_post(&full);
}
}
void *consumer(void *arg) {
while(TRUE) {
sleep(rand()%5);
sem_wait(&full);
sem_wait(&mutexC);
printf("Consuming buffer[%d] = %d\n", out, buffer[out]);
out = (out+1) % N;
sem_post(&mutexC);
sem_post(&empty);
}
}
int main(int argc, char *argv[ ]) {
pthread_t cons, prod;
sem_init(&mutexC, 0, 1);
sem_init(&mutexP, 0, 1);
sem_init(&empty, 0, N);
sem_init(&full, 0, 0);
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_exit(0);
}
我的列表实现:
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <list>
#define TRUE 1
#define N 2
using namespace std;
list<int> sharedList;
sem_t empty, full, mutexC, mutexP;
void *producer(void *arg) {
while(TRUE) {
sleep(rand()%5);
sem_wait(&empty);
sem_wait(&mutexP);
int prod = rand() % 100;
cout << "producing: " << prod << endl;
sharedList.push_back(prod);
sem_post(&mutexP);
sem_post(&full);
}
}
void *consumer(void *arg) {
while(TRUE) {
sleep(rand()%5);
sem_wait(&full);
sem_wait(&mutexC);
if (!sharedList.empty()) {
cout << "consuming: ";
cout << sharedList.front() << endl;
sharedList.pop_front();
} else {
cout << "not possible to consume" << endl;
}
sem_post(&mutexC);
sem_post(&empty);
}
}
int main(int argc, char *argv[ ]) {
pthread_t cons, prod;
sem_init(&mutexC, 0, 1);
sem_init(&mutexP, 0, 1);
sem_init(&empty, 0, N);
sem_init(&full, 0, 0);
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_exit(0);
}
来自我的实现的意外日志:
producing: 73
consuming: 73
not possible to consume
producing: 44
consuming: 44
producing: 9
producing: 65
consuming: 9
producing: 87
consuming: 65
consuming: producing: 29
87
not possible to consume
consuming: 29
producing: 9
producing: 60
consuming: 9
producing: 78
有人可以向我解释发生了什么吗? 提前致谢!
【问题讨论】:
标签: c++ pthreads producer-consumer