gpt4 book ai didi

c++ - pthread_join() 好像导致我的程序挂了,哪里出错了?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:12 25 4
gpt4 key购买 nike

我有一个小程序作为测试,如下所示:

#include<pthread.h>
#include<unistd.h>
#include<cassert>
#include<iostream>
using namespace std;
pthread_mutex_t mt;
pthread_t tid[2];
char* msg[]={"thread1","thread2"};
void* tf(void*arg){
pthread_mutex_lock(&mt);
cout<<(char*)arg<<endl;
return NULL;
}
int main(){
assert(0==pthread_mutex_init(&mt,NULL));
cout<<"step1"<<endl;
pthread_create(&tid[0],NULL,tf,msg[0]);
pthread_create(&tid[1],NULL,tf,msg[1]);
pthread_join(tid[0],NULL);
cout<<"step4"<<endl;
pthread_join(tid[1],NULL);
return 0;
}

我在 mac 上运行它并打印:

step1
thread1
step4

然后它挂起,不再运行。代码哪里出错了?非常感谢。

最佳答案

对于 pthread_mutex_lock:

The mutex object referenced by mutex shall be locked by calling pthread_mutex_lock(). If the mutex is already locked, the calling thread shall block until the mutex becomes available.

线程 2 永远等待 mt 解锁,因为您从未解锁它而线程 1 锁定了它,您应该在 tf 结束时解锁:

void* tf(void*arg){
pthread_mutex_lock(&mt);
cout<<(char*)arg<<endl;
pthread_mutex_unlock(&mt);
return NULL;
}

旁注:如果您可以访问 C++11,请考虑使用 std::mutex & std::lock_guardstd::thread 代替。

关于c++ - pthread_join() 好像导致我的程序挂了,哪里出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44780320/

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