sách gpt4 ai đã đi

c++ - 生产者和消费者——多线程

In lại Tác giả: Space Dog 更新时间:2023-10-29 20:45:03 26 4
mua khóa gpt4 Nike

我写了一个这样的多线程程序,

#include 
#include
#include
#include
#include

sử dụng không gian tên std;

pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ec = PTHREAD_COND_INITIALIZER;
pthread_cond_t fc = PTHREAD_COND_INITIALIZER;

queue qu;
const int N = 2;

void *producer(void *arg)
{
while(1) {
pthread_mutex_lock(&mu);
int tmp = rand();
qu.push(tmp);
pthread_cond_signal(&ec);
if ((int) qu.size() > N) {
pthread_cond_wait(&fc, &mu);
}
pthread_mutex_unlock(&mu);
}
}

void *consumer(void *arg)
{
while(1) {
pthread_mutex_lock(&mu);
if ((int) qu.size() < 1) {
pthread_cond_wait(&ec, &mu);
}
int tmp = qu.front();
qu.pop();
if ((int) qu.size() <= N) {
pthread_cond_signal(&fc);
}
pthread_mutex_unlock(&mu);
//sleep(1);
}
}

int chính()
{
pthread_t tid;
pthread_create(&tid, NULL, producer, NULL);
for (int i = 0; i < N; i++) {
pthread_t tid;
pthread_create(&tid, NULL, consumer, NULL);
}

printf("all created\n");

sleep(600);
}

khiqu.size()Lớn hơnNgiờ,producer停止生产,小于N时,producer恢复生产。

奇怪的问题是,如果我删除 consumer TRONG sleep(1);,程序将遇到 segmentation fault,如果我保持sleep(1);,程序运行正常。

为什么?这是否意味着 消费者 消费太快了?

1 Câu trả lời

Spurious wakeup可能是这个原因。如果条件为真,您的线程将继续,但如果您的线程继续进行,您不能假设条件为真。

Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.

比如

if (qu.size() == 0) {
pthread_cond_wait(&ec, &mu);
}

应该变成

while (qu.size() == 0) {
pthread_cond_wait(&ec, &mu);
}

关于c++ - 生产者和消费者——多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11708788/

26 4 0
Bài viết được đề xuất: c++ - boost deadline_timer 问题
Bài viết được đề xuất: Nguyên lý BODMAS trong .NET
Bài viết được đề xuất: c# - Entity Framework : Unable to load the specified metadata resource
Bài viết được đề xuất: c++ - 从 C++ 中的列表中删除元素
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com