为什么重新执行我的多线程代码后输出不一样
Why are not outputs the same after re-executing my multithreading code?
当我执行以下代码时,每次重新编译并重新执行后,答案(输出)都不一样。这是什么原因呢?
#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 test -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 test -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
由于您的线程未同步,因此执行顺序无法精确确定,并且取决于您的执行上下文,例如同时运行哪些其他进程等,每次运行程序时可能会有所不同。
是的。我用过
pthread_mutex_lock(和互斥);和pthread_mutex_unlock(和互斥体);如下
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 5
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
//sleep(1);
cout << "Hello World! Thread ID, " << tid << endl;
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main ()
{
pthread_t threads[NUM_THREADS];
int rc;
int i;
//pthread_attr_t attr;
//pthread_attr_init(&attr);
//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for( i=0; i < NUM_THREADS; i++ ){
pthread_mutex_lock(&mutex);
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
//sleep(0.5);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
我的输出始终是:
main() : creating thread, 0
Hello World! Thread ID, 0
main() : creating thread, 1
Hello World! Thread ID, 1
main() : creating thread, 2
Hello World! Thread ID, 2
main() : creating thread, 3
Hello World! Thread ID, 3
main() : creating thread, 4
Hello World! Thread ID, 4
相关文章:
- 删除原子多线程代码中的容器
- Visual Studio 发布模式阻止在调试模式下执行的代码.使用 WinHTTP 和多线程
- 开始多线程代码之前的初始化
- 实现在多线程代码中安全恢复的断点
- 一个简单的 win32 多线程代码.这能行吗?
- 混合开放MP/MPI代码中的多线程发送/接收时出错
- 为什么我的特征代码不使用更多线程扩展
- 需要帮助识别简单多线程代码中的错误
- 从C 启动多线程Python代码
- 多线程和单线程代码维护
- 在多线程代码中转发
- 为什么此 C++ 多线程互斥代码偶尔会出现故障?
- C++多线程性能比单线程代码慢
- 如何将此代码重构为多线程版本
- 为什么重新执行我的多线程代码后输出不一样
- boost::shared_ptr代码中的多线程错误
- 在多线程应用程序中的蜘蛛猴中嵌入javascript代码
- 如何改进此代码以便在多线程环境下运行
- 多线程提升 Python C++ PySide 中的代码
- C++中的单线程多线程代码