c++ - 为什么在重新执行我的多线程代码后输出不一样?

标签 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);
}

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

输出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

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

输出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

最佳答案

由于你的线程不是同步的,所以执行顺序不是精确确定的,取决于你的执行上下文,比如同时运行的其他进程等,每次运行时可能会有所不同程序。

关于c++ - 为什么在重新执行我的多线程代码后输出不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21796669/

相关文章:

c++ - 使用 NetBeans 和 MinGW gcc 编译 c++ 程序时无法运行程序 makefile

c++ - 数组还是 vector ?

c++ - 考虑STL容器操作的复杂性

c# - 在 ASP.NET 中的页面重定向之前执行长时间运行的方法

c++ - 无阻塞更新缓存

c++ - boost::condition_variable::notify_one() 的并发性

java - 创建和使用 String 对象来锁定线程同步是一个好习惯吗?

c++ - Emacs 和 gdb - 在回溯中显示函数代码

python - python 中的并行性无法正常工作

synchronization - 如果不同处理器中的两个进程试图同时获取锁会发生什么