簡體   English   中英

Pthread行為C ++

[英]Pthread behaviour C++

我已經嘗試了基本的pthreads / mutex程序:

#include<iostream>
#include<pthread.h>

using namespace std;

pthread_mutex_t mutex;

void* PrintHello(void *t)
{
    int i = reinterpret_cast<int>(t);
    pthread_mutex_lock(&mutex);
    cout<<"Hello, World thread <"<<i<<">!"<<endl;
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main()
{
    pthread_t threadId[5];
    pthread_mutex_init(&mutex, NULL);

    for(int i = 0; i < 5; i ++)
    {
        int rc = pthread_create(&threadId[i], NULL, PrintHello, reinterpret_cast<void *>(i + 1));
    }

    return 0;
}

我得到以下輸出:

執行1:

Hello, World thread <1>!
Hello, World thread <2>!
Hello, World thread <3>!
Hello, World thread <4>!
Hello, World thread <4>!
Hello, World thread <5>!

執行2:

Hello, World thread <1>!
Hello, World thread <2>!
Hello, World thread <3>!
Hello, World thread <4>!
Hello, World thread <5>!
Hello, World thread <5>!

我預計總會有五個“你好,世界!” 打印為該程序的輸出,但我看到了不同。 誰能告訴我為什么?

當主線程從main函數返回時,它使進程退出,就像調用exit函數一樣。 根據文檔 ,它將刷新stdout

所有打開的stdio(3)流都將被刷新並關閉。

可能是因為您沒有加入線程,所以主線程會刷新stdout ,而另一個線程仍在向其寫入。 因為刷新是在std::cout的析構函數中完成的,所以它不需要像通常那樣使用鎖定(因為使用已破壞對象是未定義的行為)。

還要注意, std::endl都向流中添加了換行符並將其刷新。

因此,請想象以下順序:

  1. 線程1-4打印並刷新消息。
  2. 線程5打印其消息。
  3. 主線程退出並刷新流,這無需持有通常的std::cout內部鎖即可。
  4. 線程5開始刷新std::cout ,再次刷新與步驟3中相同的消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM