Linux多线程——线程不会产生任何预期的输出
Linux Multithreading - threads do not produce any output as expected
我正在学习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;
}
不确定线程退出时是否有高休眠,这是不必要的,并且会阻止线程退出。可能不是你想要的。
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 代码编译没有任何输出,入门程序
- 可能我知道为什么这段代码没有给出任何输出吗?
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- 为什么下面的Hello World程序在PowerShell上没有显示任何输出?同一程序在CMD上显示正确的输出
- 执行此代码时,它不显示任何输出.为什么?
- 合并排序没有给我任何输出
- 编译器没有显示错误,但我没有得到任何输出.怎么了?
- 是给定代码中的任何更改,以便我可以为问题提供正确的输出
- 我的代码中是否有任何类型的错误,因为它没有给出正确的输出
- 是否可以对任何语句字符串使用预准备语句?
- 将文本文件读取到2D数组中,但数组开始为超过数组[39][]的任何内容输出胡言乱语
- 当我从头文件和实现文件调用我的函数到我的主文件时,我没有得到任何输出
- 为什么我的代码在终端中没有输出任何内容.开始新行没有错误
- 预处理器输出的差异
- 为什么我在链表中插入的代码没有得到任何输出?
- 后缀Expressrion的插图未显示任何输出
- 通过重新加载DLL,避免使用DLL预加载漏洞,任何更好的方法
- 是否有任何预处理器指令控制循环展开
- 为什么我的OpenGL引擎中没有从MyGUI获得任何屏幕输出