gpt4 book ai didi

C++ 11通过两种算法之一完成任务

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:48 25 4
gpt4 key购买 nike

我有两种算法来解决任务X()

如何为算法 1 启动一个线程,为算法 2 启动一个线程,并等待第一个算法完成,然后我杀死另一个算法并继续?

我已经看到 std::thread 中的 join 会让我等待它完成,但我不能为 join两个线程,否则我将等待两者都完成。我想同时发出它们并等待其中一个完成。实现这一目标的最佳方法是什么?

最佳答案

您无法在 C++11 中杀死线程,因此您需要安排它们的消亡。

这可以通过让它们在 std::atomic<bool> 上循环来完成变量并将获胜者带到std::call_once()以便设置返回值并标记其他线程结束。

大概是这样的:

std::once_flag once; // for std::call_once()

void algorithm1(std::atomic<bool>& done, int& result)
{
// Do some randomly timed work
for(int i = 0; !done && i < 3; ++i) // end if done is true
std::this_thread::sleep_for(std::chrono::seconds(std::rand() % 3));

// Only one thread gets to leave a result
std::call_once(once, [&]
{
done = true; // stop other threads
result = 1;
});
}

void algorithm2(std::atomic<bool>& done, int& result)
{
// Do some randomly timed work
for(int i = 0; !done && i < 3; ++i) // end if done is true
std::this_thread::sleep_for(std::chrono::seconds(std::rand() % 3));

// Only one thread gets to leave a result
std::call_once(once, [&]
{
done = true; // stop other threads
result = 2;
});
}

int main()
{
std::srand(std::time(0));

std::atomic<bool> done(false);

int result = 0;

std::thread t1(algorithm1, std::ref(done), std::ref(result));
std::thread t2(algorithm2, std::ref(done), std::ref(result));

t1.join(); // this will end if t2 finishes
t2.join();

std::cout << "result : " << result << '\n';
}

关于C++ 11通过两种算法之一完成任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626882/

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