简体   繁体   English

使用pthread_create时的奇怪输出

[英]weird output when using pthread_create

Consider the next piece of code : 考虑下一段代码:

#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;
}

I don't understand when does a thread invoke his function? 我不知道线程何时调用他的函数? Is that right as it's created? 创建时是正确的吗? (while, simultaneously, the main thread keeps on creating the other threads?) (同时,主线程继续创建其他线程吗?)

Moreover, i don't understand the output - 而且,我不明白输出-

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

First thread invoked his function twice while none of the other threads invoked theirs. 第一个线程调用了他的函数两次,而其他线程都没有调用它们的函数。

Then, i compiled again and got - 然后,我再次编译并得到-

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

Once again, what about the third thread? 再说一遍,第三个线程呢?

Why " sometimes " threads don't get to invoke their functions? 为什么“ 有时 ”线程无法调用其功能?

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

Your main function terminates before the run of the thread. 您的main函数在线程运行之前终止。 You have to wait the end of all threads before returning from the main. 从主线程返回之前,您必须等待所有线程的结束。 See this question : How can I wait for any/all pthreads to complete? 看到这个问题: 如何等待任何/所有pthread完成?

Note : You flag it as C++, any reason to not use threads from C++11 or boost ? 注意:您是否将其标记为C ++,是否不使用C ++ 11或boost的线程?

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

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