gpt4 book ai didi

c++ - 在 C++ 中并行运行线程

转载 作者:行者123 更新时间:2023-11-30 02:48:54 24 4
gpt4 key购买 nike

<分区>

我正在尝试为作业做 dekker 算法实现,我理解这个概念,但我无法使用 C++0x 并行执行两个线程。

#include <thread>
#include <iostream>

using namespace std;

class Homework2 {

public:
void run() {
try {
thread c1(&Homework2::output_one, this);

thread c2(&Homework2::output_two, this);


} catch(int e) {
cout << e << endl;
}

}

void output_one() {
//cout << "output one" << endl;
}

void output_two() {
//cout << "output two" << endl;
}


};

int main() {
try {
Homework2 p2;
p2.run();
} catch(int e) {
cout << e << endl;
}
return 0;
}

我的问题是线程会返回这个错误:

terminate called without an active exception
Aborted

到目前为止,对我来说唯一成功的方法是添加 c1.join(); c2.join();或 .detach();问题是 join();将等待线程完成,然后 detach(); ...好吧,我不确定分离是做什么的,因为没有错误但也没有输出,我想它会自行离开线程...

所以这一切要说的是:有谁知道我怎样才能让这两个线程并行运行而不是顺序运行?必须感谢您的帮助!

谢谢。-

附言:这是我为构建所做的:

g++ -o output/Practica2.out main.cpp -pthread -std=c++11 

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com