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

Nix*_*xiN 2 c++ multithreading

我在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);
}
Run Code Online (Sandbox Code Playgroud)

当我编译这段代码时,我的输出为:

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
Run Code Online (Sandbox Code Playgroud)

我的怀疑是为什么我得到这种输出,我的意思是

cout<<"Hello World! Thread num:"<<tnum<<endl;
Run Code Online (Sandbox Code Playgroud)

为什么这个语句没有按顺序执行.应该做些什么改变?有人可以帮我吗?

Ulr*_*rdt 5

你的代码有很多问题.此外,在代码之前,有一个可疑的决定使用POSIX线程而不是默认的C++线程.与古老的POSIX线程C API相比,C++线程通常与C++代码集成得更好.重新考虑这个决定!

现在,对于缺陷:

  • 不要使用C风格的演员表.如果需要,使用适当的C++投(static_cast,dynamic_cast,const_cast,reinterpret_cast).在你的情况下,你应该需要的只是static_cast.但是,您也可以reinterpret_cast在这里考虑一对s.
  • #define NUM_THREADS 5应该是int const num_threads = 5;.不要使用宏,搜索网络,找出他们为什么是邪恶的.
  • long int *tnum; tnum=(long*)threadnum;首先,这两个(声明和初始化)不应该是分开的.其次,请参阅上面有关演员表的说明.
  • pthread_exit(NULL);你在退出线程函数之前就这样做了.这有两个影响:首先,它是完全冗余的,因为退出函数(return 0;)也是如此.其次,在这里我不是100%肯定,它可能会跳过局部变量的析构函数.考虑一下析构函数在C++对象模型中的相关性,您将看到这一点至关重要.BTW:NULL很久以前使用已经皱眉了,使用0总是首选.使用C++ 11,您甚至可以使用nullptr常量.
  • pthread_create(&threads[i],NULL,PrintHello,(void*)i);除了明显糟糕的演员之外,请考虑在这里进行的转换.然后,在线程函数中查找相反的转换.提示:它不存在,它们是不对称的.
  • main(),你exit(-1);pthread_exit(NULL);.为什么不同?为什么不用return?也就是说,一个用于错误处理,为此,通常应该在C++代码中引发异常.
  • 最后,关于输出,你的假设是完全错误的.除非明确同步,否则线程独立运行.由于您不以任何方式同步它们,因此操作系统可以随意切换不同的线程,即使在一行C++代码中也是如此.