我有一个简单的程序来调用线程调用线程。我确定我显然遗漏了一些东西。下面是代码:
#include <iostream>
#include <vector>
#include <thread>
#include <unistd.h>
using namespace std;
vector<thread> threads;
void Next(int amount) {
for(int i = 0; i < amount; i++) threads.push_back(thread(Next,amount-1));
}
int main(int argc, char **argv) {
int amount = 2;
for(int i = 0; i < amount; i++) threads.push_back(thread(Next,amount-1));
cout << threads.size() << endl;
for (auto& th : threads) {
if (th.joinable()) {
th.join();
}
}
return 0;
}
输出不同,例如:
1.
2
2.
2
libc++abi.dylib: terminating
Abort trap: 6
3.
2
libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: thread::join failed: No such process
Abort trap: 6
我正在互联网上搜索任何有用的信息,但不幸的是没有找到任何东西。
我的第二个代码是什么,但我写得很好?
#include <iostream>
#include <vector>
#include <thread>
#include <unistd.h>
using namespace std;
void Next(int amount) {
vector<thread> threads;
for(int i = 0; i < amount; i++) threads.push_back(thread(Next,amount-1));
cout << threads.size() << endl;
for (auto& th : threads) {
if (th.joinable()) {
th.join();
}
}
}
int main(int argc, char **argv) {
int amount = 2;
vector<thread> threads;
for(int i = 0; i < amount; i++) threads.push_back(thread(Next,amount-1));
cout << threads.size() << endl;
for (auto& th : threads) {
if (th.joinable()) {
th.join();
}
}
return 0;
}
使用互斥量(仍然有问题):
#include <iostream>
#include <vector>
#include <thread>
#include <unistd.h>
#include <mutex>
using namespace std;
mutex mtx;
vector <thread> threads;
using namespace std;
void Next(int amount) {
for(int i = 0; i < amount; i++) {
mtx.lock();
threads.push_back(thread(Next,amount-1));
mtx.unlock();
}
}
int main(int argc, char **argv) {
int amount = 2;
for(int i = 0; i < amount; i++) {
mtx.lock();
threads.push_back(thread(Next,amount-1));
mtx.unlock();
}
cout << threads.size() << endl;
for (auto& th : threads) {
if (th.joinable()) {
th.join();
}
}
return 0;
}
最佳答案
您在访问 vector
“线程”时存在竞争条件。
关于c++ - MacOS : libc++abi. dylib 上的线程:正在终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48121119/