PTHREAD_JOIN()似乎导致我的程序悬挂,它在哪里弄错了

pthread_join() seems to lead to hang my program, where did it get wrong?

本文关键字:程序 错了 在哪里弄 我的 JOIN PTHREAD      更新时间:2023-10-16

我有一个小程序作为下面的测试:

#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_guardstd::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一起使用,所以不知道确切名称(以避免此类问题