c++中的多线程......如何执行

Multithreading in c++............how to execute?

本文关键字:执行 何执行 多线程 c++      更新时间:2023-10-16

我在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_castdynamic_castconst_castreinterpret_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++代码的中间