2013-05-29 36 views
0

我目前正在实习并要求使用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); 
} 
+3

如果你被要求使用C,那么你为什么要使用C++?如果您使用C++,为什么不使用标准线程库? –

回答

1

在你的main函数中你创建了一个竞争条件。线程可以以任意顺序启动,除非您专门同步代码,以便强制启动其中一个或另一个。因此,也不可能知道哪一个会先完成。然后,您还拥有主线程,甚至可以在您创建的线程完成之前完成。使用pthread时,您必须调用pthread_join以等待线程完成。根据因为https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal 你也应该从功能一个删除在pthread_join:你可以是这样做的:

int main(void) 
{ 
    // you pass thread thr_B to function one but 
    // function2 might even start before function1 
    // so this needs more syncronisation 
    pthread_create(&thr_A, NULL, function1, (void*)thr_B); 
    pthread_create(&thr_B, NULL, function2,NULL); 

    //this is mandatory to wait for your functions 
    pthread_join(thr_A, NULL); 
    pthread_join(thr_B, NULL); 

    return 0; 

} 

,才能在FUNCTION1等待你需要例如更先进的同步方法见例如pthread_cond_waitpthread_cond_signal作为解释man pthread join:“如果多个线程同时尝试使用相同的线程加入,则结果不确定。” 大卫hammen的评论

编辑

void * function1(void * arg) 
{ 

    cout << "You are in thread A" << endl; 
    //Remove the next line and replace by a pthread_cond_wait. 
    pthread_join(thr_B, NULL); 
    cout << "now you are again in thread A" << endl; 
    pthread_exit((void*)thr_A); 

} 
+0

这正是我想要的。谢谢。 – nihirus

+0

@nihirus如上所述,如果决定使用C++而不是C,请参阅本教程。 http://www.devx.com/SpecialReports/Article/38883它可能会节省一些工作,并且更适合于C++,尽管正确使用pthreads可以完成这项工作。如果您认为我的帖子非常有帮助,您可能想为未来的用户接受我的答案。 – hetepeperfan

+0

发布的代码是未定义的行为:*如果pthread_join()的线程参数指定的值没有引用可连接的线程,[pthread_join()]的行为是未定义的。*在这种情况下,'thr_B'不可连接在'main()'中,因为'function1'已经调用'pthread_join(thr_B,NULL);'解决方法是在这个答案中删除对'pthread_join()'的第二次调用。 –