我正在学习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;
}
答案 0 :(得分:1)
你的主线程可能会退出,因此整个过程就会消失。因此,线程没有机会运行。如果线程在主线程退出之前完成执行,即使您的代码按原样,您也可以(很不可能但仍然可能)看到线程的输出。但你不能依赖它。
调用pthread_join()
,它挂起调用线程,直到线程(由线程ID指定)返回,在main()pthread_create()
调用之后的线程上返回:
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
您还可以使用pthread_t
数组,这样就可以对for
和pthread_create()
来电使用pthread_join()
循环。
或者只使用pthread_exit(0)
退出主线程,这将仅退出调用线程,其余线程(您创建的线程)将继续执行。
请注意,您的线程函数应返回指针或NULL:
void* print (void* data)
{
cout << "Hi" << endl;
return NULL;
}
不确定线程退出的高睡眠,这是不必要的并且会阻止线程退出。可能不是你想要的东西。