c++中的多线程......如何执行
Multithreading in c++............how to execute?
我在tutorialspoint.com上学习c++中的多线程,在那里我发现了以下代码:
#include<iostream>
#include<cstdlib>
#include<pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadnum)
{
long int *tnum;
tnum=(long*)threadnum;
cout<<"Hello World! Thread num:"<<tnum<<endl;
pthread_exit(NULL);
}
int main()
{
pthread_t threads[NUM_THREADS];
int rc;
long int i;
for(i=0;i<NUM_THREADS;i++)
{
cout<<"main(): creating thread,"<<i<<endl;
rc=pthread_create(&threads[i],NULL,PrintHello,(void*)i);
cout<<"Thread ID:"<<threads[i]<<endl;
cout<<"-----------------------------------------------"<<endl;
if(rc)
{
cout<<"Error:Unable to create thread,"<<rc<<endl;
exit(-1);
}
}
pthread_exit(NULL);
}
当我编译这个代码时,我得到的输出是:
main(): creating thread,0
Thread ID:124028821706496
-----------------------------------------------
main(): creating thread,1
Thread ID:124028812797696
-----------------------------------------------
main(): creating thread,2
Hello World! Thread num:0
Thread ID:124028803434240
-----------------------------------------------
main(): creating thread,3
Hello World! Thread num:0x1
Hello World! Thread num:Thread ID:0x20x70cdb43d6700
-----------------------------------------------
main(): creating thread,4
Thread ID:124028785452800
Hello World! Thread num:0x4
-----------------------------------------------
Hello World! Thread num:0x3
我的疑问是为什么我会得到这种输出,我指的是
cout<<"Hello World! Thread num:"<<tnum<<endl;
为什么这个语句没有按顺序执行。应该做什么更改??有人能帮我吗??
您的代码有很多错误。此外,在编写代码之前,使用POSIX线程而不是默认的C++线程是一个有问题的决定。C++线程通常比POSIX线程的古C API更好地与C++代码集成。重新考虑这个决定!
现在,针对缺陷:
- 不要使用C样式强制转换。如果需要,请使用适当的C++转换(
static_cast
、dynamic_cast
、const_cast
、reinterpret_cast
)。在您的情况下,您只需要static_cast
。但是,您可能也需要考虑一对reinterpret_cast
#define NUM_THREADS 5
应该是int const num_threads = 5;
。不要使用宏,在网上搜索它们为什么是邪恶的long int *tnum; tnum=(long*)threadnum;
首先,这两者(声明和初始化)不应该是分开的。第二,请参阅上面关于铸件的注释pthread_exit(NULL);
您可以在退出线程函数之前执行此操作。这有两个效果:首先,它是完全冗余的,因为退出函数(return 0;
)也会这样做。其次,我不能百分之百肯定,它可能跳过了局部变量的析构函数。想想析构函数在C++对象模型中的相关性,你会发现这是至关重要的。BTW:使用NULL
早就不受欢迎了,使用0
一直是首选。使用C++11,您甚至有一个nullptr
常量pthread_create(&threads[i],NULL,PrintHello,(void*)i);
除了明显不好的演员阵容外,还可以考虑一下这里的转换。然后,在线程函数中查找相反的转换。提示:它不存在,它们是不对称的- 在
main()
中,您可以使用exit(-1);
或pthread_exit(NULL);
。为什么有区别?为什么不使用return
?也就是说,一个用于错误处理,为此,您通常应该在C++代码中引发异常 - 最后,关于输出,您的假设完全是错误的。线程独立运行,除非显式同步。由于您不以任何方式同步它们,因此操作系统可以随意在不同的线程之间切换,即使是在一行C++代码的中间
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 如何在C++中执行以前执行的代码行
- 为什么我的虚拟破坏者多次执行这些执行
- 如何标识其功能当前正由可执行文件执行的共享库
- 打印C 代码执行逐步执行
- 从编译的可执行文件执行函数
- 当程序执行取决于执行顺序时,是否是未定义的行为
- 在.so内部定义的extern变量和可执行引线执行未定义的行为
- 等待执行不可执行脚本的子进程
- 调试与发布可执行文件有何不同?