pthread_join()似乎导致挂起我的程序,它出错了哪里?

Hin*_*sum 1 c++ multithreading pthreads

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

我在mac上运行它并打印:

step1
thread1
step4
Run Code Online (Sandbox Code Playgroud)

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

Som*_*ken 6

用于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;
}
Run Code Online (Sandbox Code Playgroud)

附注:如果你有机会到C++ 11使用考虑std::mutexstd::lock_guardstd::thread代替.