gpt4 book ai didi

c++ - 用于在 C++ 中同步线程的二进制信号量

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:58:35 24 4
gpt4 key购买 nike

大家。我是信号量的新手,最近我正在学习使用二进制信号量来实现一个简单的问题,我有一些问题。

所以有一个探视室,一次只能一个人进去。我的设计是三个队列的人(都是我创建的线程)。例如,第二个队列的人访问了那个房间后,下一个要进入房间的人是第三个队列中等待的第一个,而不是第一个队列的人。给出了总人数。离开后,只需简单地终止线程即可。

我正在尝试创建三个信号量来处理这个问题,即在第二个队列中的一个人进入后,然后阻止第二个队列并仅“发出信号”让第三个队列继续。等等等等。但是,代码有一些问题。这里我只展示了一些信号量部分的代码。

主要内容:

sem_init(&mutex, 0, 1);

sem_init(&s0, 0, 1);

sem_init(&s1, 0, 1);

sem_init(&s2, 0, 1);

//创建100个pthread随机放入queue0或queue1或queue2

 for(int i = 0; i<num_thread; i++){ 

pthread_t curr_thread;
if(queueId == 0){
queue0.push(curr_thread);
}else if(queueId == 1){
queue1.push(curr_thread);
}else if(queueId == 2){
queue2.push(curr_thread);
}
pthread_attr_t attr;
pthread_attr_init (&attr);
pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
pthread_create (&curr_thread, &attr, &thread_function, &queue_Num);
pthread_attr_destroy (&attr);

}

在线程函数中:

void* thread_function (void* arg){

sem_wait(&mutex);

int n = *((int*) arg);
if(n==0){
sem_wait(&s0);
cout << "person in queue" << n << " is visiting" << endl;
sleep(1);
if(!queue0.empty()){
queue0.pop();
}else{
n++;
}
sem_post(&s1);

}else if(n==1){
sem_wait(&s1);
cout << "person in queue" << n << " is visiting" << endl;
sleep(1);
if(!queue1.empty()){
queue1.pop();
}else{
n++;
}
sem_post(&s2);
}else if(n==2){
sem_wait(&s2);
cout << "person in queue" << n << " is visiting" << endl;
sleep(1);
if(!queue2.empty()){
queue2.pop();
}else{
n++;
}
sem_post(&s0);
}

sem_post(&mutex);

return NULL;
}

实际上,当我运行它时,似乎遇到了“死锁”,主线程每次只显示 2 个线程。我认为thread_function的设计一定有问题。有没有人可以帮助指出并告诉我如何解决它?提前致谢。

最佳答案

当您将 queueId 传递给线程时,您不想将它传递给一个指向局部变量的指针,因为您将很快改变它。相反,您应该将整数本身传递给您的线程:

pthread_create(&curr_thread, &attr, &thread_function, (void*)queueId);
// Pass queueId the int, not a pointer

然后,当您需要在线程中读取值时,只需将 void* 转换回整数即可:

void* thread_function (void* arg){
...

int n = (long)arg;

..
}

在此之后,您的代码对我来说效果很好。

关于c++ - 用于在 C++ 中同步线程的二进制信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13734738/

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