繁体   English   中英

C ++中的Pthread使用

[英]Pthread Usage in 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);
}

在主要功能中,您将创建一个竞态条件。 线程可以以任何顺序启动,除非您专门同步代码,以便您强制一个或另一个启动。 因此,也无法确定哪个将首先完成。 然后,您还有主线程,它甚至可能在创建的线程完成之前完成。 使用pthread时,必须调用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_wait pthread_cond_signal如下所述: https : //computing.llnl.gov/tutorials/pthreads/#ConVarSignal您还应该从函数一中删除pthread_join,因为根据man pthread join:“如果多个线程同时尝试与同一个线程连接,则结果是不确定的。”

编辑 David 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);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM