c++ - MacOS : libc++abi. dylib 上的线程:正在终止

标签 c++ multithreading macos

我有一个简单的程序来调用线程调用线程。我确定我显然遗漏了一些东西。下面是代码:

#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/

相关文章:

javascript - 从 C++(Node.js 插件)调用 C 库时出现 "Symbol Lookup Error"

c++ - 在函数声明中尾随 const& 或 &&

java - 如何让线程等待服务器响应

swift - NSTextField:将 String 转换为 Int 在 Xcode 外部中止(nil)

macos - Mac OS X 上的 Visual Source Safe

Java:如何获得永不更改的计算机的唯一序列号

c++ - 将 SDL、SFML 或 GLFW 挂接到现有的 OpenGL 应用程序中

c++ - 在 Boost (C++) 中没有类跟踪的派生类序列化

c++ - 'std::thread' 的初始化没有匹配的构造函数

java - 多线程 QuickSort 比普通 QuickSort 花费更长的时间