以下面的代码为例。在pthread_con_wait中,activeMutex被锁定。然后是行“pthread_mutex_unlock(& activeMutex)”必要?因为主要功能即将结束。或者,如果我删除该行,主完成后互斥锁将自动解锁。是否有必要在主结束时解锁互斥锁?
#include <pthread.h>
#include <iostream>
using namespace std;
int activeThreads = 0;
pthread_mutex_t coutMutex;
pthread_mutex_t activeMutex;
pthread_cond_t allDoneCondition;
void* Thread(void* v)
{
unsigned long myId = (unsigned long)v;
pthread_mutex_lock(&coutMutex);
cout << "Hello from thread " << myId << endl;
pthread_mutex_unlock(&coutMutex);
pthread_mutex_lock(&activeMutex);
activeThreads--;
if (activeThreads == 0)
{
pthread_cond_signal(&allDoneCondition);
}
pthread_mutex_unlock(&activeMutex);
}
int main(int argc, char** argv)
{
int totalThreads = 8;
pthread_mutex_init(&coutMutex, 0);
pthread_mutex_init(&activeMutex, 0);
pthread_cond_init(&allDoneCondition, 0);
pthread_mutex_lock(&activeMutex);
activeThreads = totalThreads;
for (int i = 0; i < totalThreads; ++i)
{
pthread_t t;
pthread_create(&t, 0, Thread, (void*)i);
}
cout << "Hello from main before exit" << endl;
pthread_cond_wait(&allDoneCondition, &activeMutex);
pthread_mutex_unlock(&activeMutex);
}
使用C++的正确,使之成为非问题。清理干净的东西。当你用这个代码的模糊的记忆,包起来一起10年晚一点到一些其他项目库 – GManNickG