C++ 11 std :: thread join在Xcode 6上遇到system_error异常和SIGABRT崩溃?

sta*_*son 4 c++ multithreading sigabrt c++11

这是一个简单的线程跟踪程序.线程只打印前十个整数,然后打印"线程完成"消息.

#include <iostream>
#include <vector>
#include <numeric>
#include <thread>

void f();

int main(int argc, const char * argv[]) {
    std::thread t(f);

    std::cout << "Thread start" << std::endl;

    t.detach();
    t.join();

    std::cout << "Thread end" << std::endl;

    return 0;
}

void f()
{
    std::vector<int> a(10);
    std::iota(a.begin(), a.end(), 0);

    for(const int& i : a)
    {
        std::cout << i << std:: endl;
    }
    std::cout << "Thread is done." << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但是,当它运行时,t.join会在libc ABI中的某处抛出一个std :: __ 1 :: system_error异常,导致程序以SIGABRT终止:

Thread start
0
1
2
3
4
5
6
7
8
9
Thread is done.
libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: thread::join failed: No such process
Run Code Online (Sandbox Code Playgroud)

有时当它运行时,主线程中的异常在线程t运行之前发生(在同一个地方)(但它仍然存在):

Thread start
libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: thread::join failed: No such process
0
1
2
3
4
5
6
7
8
9
Thread is done.
Run Code Online (Sandbox Code Playgroud)

Dav*_*e S 5

问题在于,分离和连接都有一个前提条件,即线程是可连接的,并且两者都具有可连接为false的后置条件.这意味着一旦你在一个线程上调用一个,尝试调用另一个是无效的.

其次,您看到的不同行为是由于执行线程和主要功能的时间.有时,分离和连接直到线程运行后才执行,有时它们之前运行,以及之间的任何内容.