[英]C++11 std::thread join crashes with system_error exception and SIGABRT on Xcode 6?
這是一個簡單的線程跟蹤程序。 該線程僅打印前十個整數,然后顯示“線程已完成”消息。
#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.
可能是嘗試加入未啟動的線程的結果。
當我為這樣的線程加入一個數組時,我收到了這個錯誤:
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;
}
std::thread 在構造后開始執行。 因此不需要分離。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.