簡體   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