繁体   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