gpt4 book ai didi

c++ - pthread_cond_broadcast 之前的同步

转载 作者:行者123 更新时间:2023-11-28 05:15:42 25 4
gpt4 key购买 nike

我想从主线程向等待条件的所有其他线程发送广播信号。在我看来,广播信号来得早。

#include <iostream>
#include <pthread.h>

#define NUM 4
#define SIZE 256

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_barrier_t barrier;

class cache{
int lv1;
public:
int write(int i){
lv1=i;
pthread_cond_broadcast(&cond);
}
};

cache c[NUM];

void *thread(void *arg){
int i = (int)arg;
for(;;){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
cout << "Thread: "<< i << endl;
//do some work
pthread_mutex_unlock(&mutex);
}
}


int main()
{
pthread_t tid[NUM];
pthread_barrier_init(&barrier,NULL,NUM+1);

for(int i=0;i<NUM;i++){
pthread_create(&tid[i],NULL,thread,(void*)i);
}

//Sleep(2);
c[0].write(55); //broadcast signal
//Sleep(2);
c[1].write(44); //broadcast signal

for(int i=0;i<NUM;i++){
pthread_join(tid[i],NULL);
}

cout << "Hello world!" << endl;
return 0;
}

如果我在主函数中插入 Sleep(2),它会工作,但我不想等待时间,而是在调用 pthread_broadcast 之前等待同步。想到了barrier,但是pthread_cond_wait是阻塞的吧?

最佳答案

您需要了解如何使用条件变量。您还错误地处理了线程的整数参数。这是一个固定版本,希望与您想要的相似:

#include <iostream>
#include <pthread.h>
#include <unistd.h>

#define NUM 4
#define SIZE 256

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_barrier_t barrier;

class cache{
int lv1;
public:
int write(int i) { lv1=i; }
const int val() { return lv1; }
};

cache c[NUM];

void *thread(void *arg)
{
int i = *(int*)arg;
for(;;) {
pthread_mutex_lock(&mutex);
// Check predicate, do not go to sleep if predicate is fulfilled
if (c[0].val() > 0 && c[1].val() > 0) {
cout << "Thread " << i << " leaving...\n";
pthread_mutex_unlock(&mutex);
return 0;
}
pthread_cond_wait(&cond, &mutex);
cout << "Thread wakeup: "<< i << endl;
// do some work
pthread_mutex_unlock(&mutex);
}
}


int main()
{
pthread_t tid[NUM];

int arg[NUM];
for(int i=0; i<NUM; i++) {
arg[i] = i; // make a copy of i used by only one thread
pthread_create(&tid[i], NULL, thread,(void*)&arg[i]);
}

pthread_mutex_lock(&mutex);
c[0].write(55);
c[1].write(44);
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond); // Signal all threads that predicate is fulfilled


for(int i=0; i<NUM; i++) {
pthread_join(tid[i],NULL);
cout << "Joined " << i << '\n';
}

cout << "Hello world!" << endl;
return 0;
}

关于c++ - pthread_cond_broadcast 之前的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42721769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com