在windows下使用pthreads。 如果等待另外一个线程结束的话,用pthread_join 和pthread_cond_wait哪个更好?
我使用的是pthreads-w32-2-8-0-release。我的程序是一个dll,被别人的exe调用。核心类叫做CProcessor。
Class CProcessor
{
//...
bool active;
bool terminated;//线程结束标志
pthread_t threadId;
pthread_mutex_t mutex;
pthread_cond_t cond;
static void* AlgoThreadFunc(void* data);
//...
};
我在构造函数中创建子线程
active = true;
terminated = false;
int result = pthread_create(&(this->threadId), NULL, AlgoThreadFunc, (void*)this);
在析构函数中等待子线程结束---必须等待,因为AlgoThreadFunc中涉及很多资源分配。
我采用pthread_cond_wait来等待
active = false;
if (!terminated)
{
pthread_mutex_lock(&mutex);//lock
pthread_cond_wait(&cond, &mutex);//wait for signal
pthread_mutex_unlock(&mutex);
}
//...
线程体结构如下
void* CProcessor::AlgoThreadFunc(void* data)
{
CProcessor* processor = (CProcessor*) data;
if (processor)
{
while (processor->isActive())
{
//有意义的代码,此处略
Sleep(5);
}
//发消息通知主线程
pthread_cond_signal(&(processor->cond));
processor->terminated = true;
}
return NULL;
}
但是我在运行时发现用户关闭程序时,析构函数未执行完,程序僵死不释放资源。