奇怪的线程打印行为

Jos*_*ury 1 c++ multithreading pthreads

嘿 - 我写的一个小玩具程序有一个奇怪的问题,试试线程.
这是我的代码:

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

using std::cout;
using std::endl;

void *threadFunc(void *arg) {
    cout << "I am a thread. Hear me roar." << endl;

    pthread_exit(NULL);
}

int main() {
    cout << "Hello there." << endl;
    int returnValue;
    pthread_t myThread;

    returnValue = pthread_create(&myThread, NULL, threadFunc, NULL);

    if (returnValue != 0) {
        cout << "Couldn't create thread! Whoops." << endl;
        return -1;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

主要的第一个cout没有注释掉,线程打印很好.
但是,没有它,线程根本不会打印任何东西.

有帮助吗?

小智 5

试试这个:

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

using std::cout;
using std::endl;

void *threadFunc(void *arg) {
    cout << "I am a thread. Hear me roar." << endl;

    pthread_exit(NULL);
}

int main() {
    //cout << "Hello there." << endl;
    int returnValue;
    pthread_t myThread;

    returnValue = pthread_create(&myThread, NULL, threadFunc, NULL);

    if (returnValue != 0) {
        cout << "Couldn't create thread! Whoops." << endl;
        return -1;
    }

    pthread_join( myThread, NULL);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的代码和你的代码之间的区别是一行 - pthread连接.这将挂起主线程,直到子线程有机会完成其操作.

在您的代码中,执行到达第一个cout并进行处理.然后,您拆分另一个线程,主线程一直持续到结束,在辅助线程整理之前可能会或可能不会到达.这就是奇怪行为的来源 - 您遇到的情况是主程序在子线程有机会之前完成的情况,因此程序已"返回"并且整个批次由内核清理.