我有简单的程序来调用线程调用线程。我确定我明显遗漏了一些东西。下面是代码:
#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;
}
答案 0 :(得分:0)
您在访问vector
&#39;线程时遇到竞争条件。