重新执行多线程代码后,为什么输出不相同?

Cod*_*ode 1 c++ multithreading synchronization

当我执行以下代码时,每次重新编译并重新执行后,答案(输出)都不一样.这是什么原因?

 #include <iostream>
#include <cstdlib>
//#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   cout << "Hello World! Thread ID, " << tid << endl;
   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads[NUM_THREADS];
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL, 
                          PrintHello, (void *)i);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}
Run Code Online (Sandbox Code Playgroud)

g ++ test.cpp -o test -lpthread ./test

输出1:

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
Hello World! Thread ID, 0
main() : creating thread, 3
Hello World! Thread ID, 1
Hello World! Thread ID, 2
main() : creating thread, 4
Hello World! Thread ID, 3
Hello World! Thread ID, 4
Run Code Online (Sandbox Code Playgroud)

g ++ test.cpp -o test -lpthread ./test

输出2:

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
Hello World! Thread ID, 0
main() : creating thread, 4
Hello World! Thread ID, 3
Hello World! Thread ID, 2
Hello World! Thread ID, 4
Hello World! Thread ID, 1
Run Code Online (Sandbox Code Playgroud)

Mar*_* J. 5

由于您的线程未同步,因此执行顺序并未精确确定,并且取决于您的执行上下文,例如同时运行的其他进程等,每次运行程序时可能会有所不同.