【发布时间】:2010-01-28 18:28:34
【问题描述】:
嘿 - 我编写的一个小玩具程序遇到了一个奇怪的问题,用于尝试线程。
这是我的代码:
#include <pthread.h>
#include <iostream>
using std::cout;
using std::endl;
void *threadFunc(void *arg) {
cout << "I am a thread. Hear me roar." << endl;
pthread_exit(NULL);
}
int main() {
cout << "Hello there." << endl;
int returnValue;
pthread_t myThread;
returnValue = pthread_create(&myThread, NULL, threadFunc, NULL);
if (returnValue != 0) {
cout << "Couldn't create thread! Whoops." << endl;
return -1;
}
return 0;
}
由于 main 中的第一个 cout 没有被注释掉,线程打印正常。
但是,没有它,线程根本不会打印任何内容。
有什么帮助吗?
【问题讨论】:
-
请记住,默认情况下 C++ 流不是线程安全的。同时在多个线程中写入 cout 可能会导致问题。通常在周六凌晨 3:00 之前未被检测到,此时客户端调用并说服务器崩溃了......
标签: c++ multithreading pthreads