Linux多线程——线程不会产生任何预期的输出

Linux Multithreading - threads do not produce any output as expected

本文关键字:任何预 输出 多线程 线程 Linux      更新时间:2023-10-16

我正在学习Linux平台的多线程。我编写这个小程序是为了熟悉这些概念。在运行可执行文件时,我看不到任何错误,也没有打印Hi。因此,在看到输出后,我让线程进入睡眠状态。但仍然无法在控制台上看到打印。

我还想知道哪个线程在运行时打印。有人能帮我吗?

#include <iostream>
#include <unistd.h>
#include <pthread.h>
using std::cout;
using std::endl;
void* print (void* data)
{
      cout << "Hi" << endl;
      sleep(10000000);
}
int main (int argc, char* argv[])
{
   int t1 = 1, t2 =2, t3 = 3;
   pthread_t thread1, thread2, thread3;
   int thread_id_1, thread_id_2, thread_id_3;
   thread_id_1 = pthread_create(&thread1, NULL, print, 0);
   thread_id_2 = pthread_create(&thread2, NULL, print, 0);
   thread_id_3 = pthread_create(&thread3, NULL, print, 0);
   return 0;
 }

您的主线程可能退出,因此整个进程死亡。因此,线程没有机会运行。如果线程在主线程退出之前完成了执行,那么即使代码按原样运行,也有可能看到线程的输出(虽然不大可能,但仍然有可能)。但是你不能依赖它。

调用pthread_join(),在pthread_create()调用main()后的线程上挂起调用线程,直到线程(由线程ID指定)返回:

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);

您还可以使用pthread_t数组,这将允许您在pthread_create()pthread_join()调用上使用for循环。

或者使用pthread_exit(0)仅退出主线程,这将仅退出调用线程,其余线程(您创建的线程)将继续执行。

注意你的线程函数应该返回一个指针或者NULL:

void* print (void* data)
{
    cout << "Hi" << endl;
    return NULL;
}

不确定线程退出时是否有高休眠,这是不必要的,并且会阻止线程退出。可能不是你想要的。

相关文章: