我目前正在实习并要求使用C++编写多客户端服务器客户端应用程序。因此,我试图学习线程。有一个问题:C++中的线程使用情况
我想打印“你在线程A”,然后“你在线程B”,“现在你又回到了线程A”。但它只打印前两个句子并忽略endl命令。无法准确理解它是如何工作的。如何解决这个问题,你能简要解释一下工作机制吗?
为什么主线程在所有函数调用完成之前退出?
void * function1(void * arg);
void * function2(void * arg);
pthread_t thr_A, thr_B;
int main(void)
{
pthread_create(&thr_A, NULL, function1, (void*)thr_B);
pthread_create(&thr_B, NULL, function2,NULL);
return 0;
}
void * function1(void * arg)
{
cout << "You are in thread A" << endl;
pthread_join(thr_B, NULL);
cout << "now you are again in thread A" << endl;
pthread_exit((void*)thr_A);
}
void * function2(void * arg)
{
cout << " you are in thread B " << endl ;
pthread_exit((void*)thr_B);
}
如果你被要求使用C,那么你为什么要使用C++?如果您使用C++,为什么不使用标准线程库? –