C++ 奇怪的丝印行为
嘿-我写的一个小玩具程序有一个奇怪的问题,用来尝试线程。C++ 奇怪的丝印行为,c++,multithreading,pthreads,C++,Multithreading,Pthreads,嘿-我写的一个小玩具程序有一个奇怪的问题,用来尝试线程。 这是我的代码: #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); } in
这是我的代码:
#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;
}
#包括
#包括
使用std::cout;
使用std::endl;
void*threadFunc(void*arg){
cout它在一种情况下工作的事实纯粹是运气。你有一个计时问题,那就是你的程序在线程工作之前退出
当main()
退出时,所有线程都将死亡。在main()
最终,您需要某种运行循环和消息传递/事件来在线程之间进行通信
-jeff它在一种情况下工作的事实纯粹是运气。您有一个计时问题,即您的程序在线程工作之前退出
当main()
退出时,所有线程都将死亡。在main()
最终,您需要某种运行循环和消息传递/事件来在线程之间进行通信
-jeff尝试添加pthread\u出口(空);
在main的末尾,在返回0
之前。我怀疑问题在于main
返回并且进程在线程有机会打印之前退出。从main
打印可能会以某种方式修改计时,使线程有机会打印——但这纯粹是运气。您不需要这样做o确保在所有线程完成工作之前,main不会返回。从main调用pthread\u exit
允许其他线程继续运行,直到它们也调用了pthread\u exit
尝试添加pthread\u exit(NULL);
在main的末尾,在返回0
之前。我怀疑问题在于main
返回并且进程在线程有机会打印之前退出。从main
打印可能会以某种方式修改计时,使线程有机会打印——但这纯粹是运气。您不需要这样做o确保在所有线程完成工作之前,main不会返回。从main调用pthread\u exit
允许其他线程继续运行,直到它们也调用了pthread\u exit
尝试以下操作:
#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;
}
pthread_join( myThread, NULL);
return 0;
}
#包括
#包括
使用std::cout;
使用std::endl;
void*threadFunc(void*arg){
试试这个:
#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;
}
pthread_join( myThread, NULL);
return 0;
}
#包括
#包括
使用std::cout;
使用std::endl;
void*threadFunc(void*arg){
cout这是一种竞争条件,允许程序在主循环运行一段时间后运行。程序在线程有机会运行之前退出
在从main()返回之前,您应该等待线程完成(请参见pthread_join
)。这是一种竞赛条件,允许程序在主循环运行一段时间后工作。您的程序在线程有机会运行之前就退出了
您应该等待线程完成(请参阅pthread\u join
),然后再从main()返回在默认情况下,C++流不是线程安全的。在多个线程中同时写入CUT会导致问题。通常在星期六凌晨3:00未检测到客户端调用并说服务器崩溃时,请记住,C++流在默认情况下不是线程安全的。我的时间会导致问题。通常在周六凌晨3点客户端打电话说服务器崩溃时才被发现。。。