这是一个简单的线程跟踪程序。线程只打印前十个整数,然后打印“线程完成”消息。
#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;
}
但是,当它运行时,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
有时当它运行时,主线程中的异常在线程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.
答案 0 :(得分:5)
问题在于,分离和连接都有一个前提条件,即线程是可连接的,并且两者都具有可连接为false的后置条件。这意味着一旦你在一个线程上调用一个,尝试调用另一个是无效的。
其次,您所看到的不同行为是由于执行线程和主要功能的时间。有时,分离和连接直到线程运行后才执行,有时它们之前运行,以及之间的任何内容。
答案 1 :(得分:1)
可能是尝试连接未启动的线程的结果。
当我为这样的线程加入一个数组时,我收到了这个错误:
for (auto& th : threads) th.join();
然后我重写了一个手册for循环,没有给我任何错误:
for (i = 0; i< numthreads; i++)
threads[i] = thread(start,i+1);
我认为这是因为我声明了这样的数组:
std::thread threads[MAXTHREADS];
所以它试图加入我没有开始的线程。
完整的参考代码:
#include <sched.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <thread> // std::thread
#include <mutex> // std::mutex
using namespace std;
mutex mtx; // mutex for critical section
#define MAXTHREADS 10
#define MAXTIMES 1
int data[MAXTHREADS];
int start(int id) {
int stride = 64, dummy;
mtx.lock();
for(int times = 0; times < MAXTIMES; times++) {
for (int i = 0; i < MAXTHREADS; i = i + 1) {
//dummy = data[i]; //sim a read from every slot in the array
cout << data[i] << ", ";
}
cout << endl;
}
mtx.unlock();
return 0;
}
int main()
{
std::thread threads[MAXTHREADS];
int i;
int numthreads = 6;
for(int i = 0; i < MAXTHREADS; i++)
data[i] = i;
printf("Creating %d threads\n", numthreads);
for (i = 0; i< numthreads; i++)
threads[i] = thread(start,i+1);
for (i = 0; i< numthreads; i++)
threads[i].join();
//for (auto& th : threads) th.join();
printf("All threads joined\n");
return 0;
}
答案 2 :(得分:-2)
std :: thread在构造之后开始执行。因此不需要分离。