您好,我是多线程编程的新手。我正在尝试创建一个创建线程 THREAD1 的代码,在它完成某些操作后,它会触发另外两个线程,比如 THREAD2 和 THREAD3,然后退出。
我写了两个可能的解决方案。
1)使用条件变量(不工作:在某些情况下我遇到了死锁):
pthread_mutex_t ready_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ready_cond = PTHREAD_COND_INITIALIZER;
bool ready = false;
void* trigger(void*);
void* func1(void*);
void* func2(void*);
int main()
{
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_create(&thread1, 0, &trigger, 0);
pthread_create(&thread2, 0, &func1, 0);
pthread_create(&thread3, 0, &func2, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
pthread_join(thread3, 0);
}
void *trigger(void*)
{
pthread_mutex_lock(&ready_mutex);
ready = true;
pthread_cond_broadcast(&ready_cond);
pthread_mutex_unlock(&ready_mutex);
return 0;
}
void *func1(void*)
{
while (!ready) // Needed to avoid spuriuos wake-up
{
pthread_mutex_lock(&ready_mutex);
pthread_cond_wait(&ready_cond, &ready_mutex);
pthread_mutex_unlock(&ready_mutex);
}
std::cout << "In 'func1'>> Do something" << std::endl;
return 0;
}
void *func2(void*)
{
while (!ready) // Needed to avoid spuriuos wake-up
{
pthread_mutex_lock(&ready_mutex);
pthread_cond_wait(&ready_cond, &ready_mutex);
pthread_mutex_unlock(&ready_mutex);
}
std::cout << "In 'func2'>> Do something" << std::endl;
return 0;
}
2) THREAD1 直接创建另外两个线程。
pthread_mutex_t ready_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ready_cond = PTHREAD_COND_INITIALIZER;
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
void* trigger(void*);
void* func1(void*);
void* func2(void*);
int main()
{
pthread_create(&thread1, 0, &trigger, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
pthread_join(thread3, 0);
}
void *trigger(void*)
{
std::cout << "In 'trigger'>> Do something" << std::endl;
pthread_create(&thread2, 0, &func1, 0);
pthread_create(&thread3, 0, &func2, 0);
return 0;
}
void *func1(void*)
{
std::cout << "In 'func1'>> Do something" << std::endl;
return 0;
}
void *func2(void*)
{
std::cout << "In 'func2'>> Do something" << std::endl;
return 0;
}
我想知道你的意见。非常感谢