PTHREAD_JOIN()似乎导致我的程序悬挂,它在哪里弄错了
pthread_join() seems to lead to hang my program, where did it get wrong?
我有一个小程序作为下面的测试:
#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
:
互在引用的静音对象应通过调用来锁定
pthread_mutex_lock()
。如果静音已经锁定,请调用 螺纹应阻止直到二线可用。
线程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
&amp;std::lock_guard
和std::thread
而不是。
您应该致电pthread_mutex_unlock解锁互斥s,让第二个线程完成工作:
void* tf(void*arg){
pthread_mutex_lock(&mt);
cout<<(char*)arg<<endl;
pthread_mutex_unlock(&mt); // <=== here
return NULL;
}
如果未执行解锁,则第二个线程将永远等待sutex,并且程序"悬挂"。
如果必须在程序中使用 pthreads ,则可以考虑编写一些 raii 包装器以避免使用此类错误。
您应该解锁Mutex以允许第二个线程执行tf((函数。现在,穆特克斯被第一线程锁定(第一个是指启动ft((执行(而永不解锁的第一个。我还建议使用STD :: lock_guard(从未与pthread_mutex_t一起使用,所以不知道确切名称(以避免此类问题
相关文章:
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- 首要问题的答案让值班员搞错了
- 看起来is_nothrow_constructible_v()在MSVC中被破坏了,我错了吗
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 我的C++线程做错了什么?
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我对这个程序有问题.有人看到我做错了什么吗?对此相当陌生
- PTHREAD_JOIN()似乎导致我的程序悬挂,它在哪里弄错了
- 每当我运行此程序C 时,我都会出现错误.我做错了什么
- 我在给定程序中错了
- 计算器程序总是输出 0 - 我做错了什么
- 素数程序-我做错了什么
- 为什么这个程序会崩溃?我分配内存错了吗
- 我的while程序溢出了?我做错了什么?
- 程序不会编译-我做错了什么
- 我的程序应该摆脱不是数字的字符,但不能完全工作,关于我做错了什么有什么想法吗?
- 我哪里做错了?程序未读取"outstanding"和"unsatisfactory"变量
- C#,我的程序在函数运行后停止运行,我做错了什么
- 基本的c++程序,我做错了什么