【问题标题】:weird output when using pthread_create使用 pthread_create 时的奇怪输出
【发布时间】:2016-04-20 08:19:53
【问题描述】:

考虑下一段代码:

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

using namespace std;

pthread_t tid[3];

void* printMe(void* arg)
{
    pthread_t id = pthread_self();
    if(pthread_equal(id,tid[0]))
    {
        cout << "first thread's in function" << endl;
    }
    if(pthread_equal(id,tid[1]))
    {
        cout << "second thread's in function" << endl;
    }
    if(pthread_equal(id,tid[2]))
    {
        cout << "third thread's in function" << endl;
    }

}

int main() {

    int i = 0;
    int err;

    while (i < 3)
    {
        err = pthread_create(&(tid[i]), NULL, printMe, NULL);

        if (err != 0)
        {
            cout << "failed to create thread number " << i << strerror(i) << endl;
        }
        else
        {
            cout << "main() : creating thread number " << i << endl;
        }

        i++;
    }

    return 0;
}

我不明白线程什么时候调用他的函数? 这是正确的,因为它是创建的? (同时,主线程继续创建其他线程?)

此外,我不明白输出 -

main() : creating thread number 0
main() : creating thread number 1
main() : creating thread number 2
first thread's in function
first thread's in function

第一个线程调用了他的函数两次,而其他线程都没有调用它们的函数。

然后,我再次编译得到 -

main() : creating thread number 0
first thread's in function
main() : creating thread number 1
second thread's in function
main() : creating thread number 2

再说一遍,第三个线程呢?

为什么“有时”线程不能调用它们的函数?

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    您的主函数在线程运行之前终止。在从主线程返回之前,您必须等待所有线程结束。 看到这个问题:How can I wait for any/all pthreads to complete?

    注意:您将其标记为 C++,有什么理由不使用 C++11 或 boost 中的线程?

    【讨论】:

    • 谢谢!这是因为我正在做一个不允许我们使用 boost 的学校项目。艰难的生活
    • “有什么理由不使用 boost 中的线程?” - >= C++11-capable 编译器应该首选标准库线程......
    • @TonyD :我同意这一点,我在工作中仅限于 gcc 4.1.2,然后我仍在考虑 C++98。
    • @Caduchon:随着我花时间获取和重建第 3 方包,有人曾经用 VS2008 构建并提交了二进制文件,因此我们可以完成向 VS2013 和 64 位的迁移并使用 C++11 -我也会认真考虑使用 gcc 4.1.2。干杯。
    【解决方案2】:

    您的main() 在返回之前没有加入线程并因此终止程序,因此您是否看到任何给定线程的输出或多或少是随机的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      相关资源
      最近更新 更多