c++ - 这种基于线程 ID 的同步是否安全且整洁?
问题描述
我编写了一个解决 IQ Twist 谜题的小型 AI 程序。然后作为练习,我将其并行化。这是来源: IQTwist 解析器。
搜索解决方案的算法是递归的。
我在递归函数的关键部分(将找到的形状收集到成员数组)中使用了基于线程 ID 的同步。我指的关键部分:
bool IQTwistResolver::searchForSolution(const int type, const uint32 a_union)
{
if (m_stopSearch) //make all other threads unwind recursion and finish
return false;
if (TYPES_COUNT == type) //all types reached and solved - end recursion
{
m_mutex.lock();
if (std::thread::id::id() == m_firstFinder || std::this_thread::get_id() == m_firstFinder)
{
m_firstFinder = std::this_thread::get_id();
m_stopSearch = true;
}
m_mutex.unlock();
return true; //return true to collect the solution and unwind
}
...
我正在尝试寻求专家的建议:
这种方法是否有任何可能的弱点/缺陷或矫枉过正(也许我错过了一些更简单的解决方案)?
您会使用不同的“解决方案缓冲区”保护方法吗?
也许您会使用完全不同的并行化方案(这也值得知道)?
解决方案
您的解决方案应该按预期工作,但是,使用std::mutex
是最通用和最昂贵的解决方案。
另一种选择是使用std::call_once
它确保只有第一个线程进行调用。即第一个找到解决方案的线程将设置搜索结果的值。
或者,您可以使用std::atomic
来避免使用互斥锁。而不是线程id,一个线程特定变量的地址就足以在线程之间进行区分。
例如:
#include <iostream>
#include <atomic>
#include <thread>
class FirstThread {
static thread_local std::thread::id const thread_id_;
std::atomic<std::thread::id const*> first_{0};
public:
std::thread::id const& id() const noexcept {
return thread_id_;
}
bool try_become_first() noexcept {
std::thread::id const* expected = 0;
return first_.compare_exchange_strong(expected, &thread_id_, std::memory_order_relaxed, std::memory_order_relaxed);
}
bool is_first() const noexcept {
return first_.load(std::memory_order_relaxed) == &thread_id_;
}
};
thread_local std::thread::id const FirstThread::thread_id_ = std::this_thread::get_id();
int main() {
FirstThread ft;
auto f = [&ft]() {
ft.try_become_first();
std::cout << "thread " << ft.id() << " is first: " << ft.is_first() << '\n';
};
f();
std::thread(f).join();
}
输出:
thread 139892443997984 is first: 1
thread 139892384220928 is first: 0
请注意,如果您不需要返回的真实线程 id std::this_thread::get_id()
,则可以只使用特定于线程的地址bool
来标识不同的线程。
推荐阅读
- angular - 如何避免在调度新操作时通过循环访问存储对象而重新渲染组件
- amazon-web-services - 添加额外的 DNS pod 如何配置和处理
- android - Google play:由于 64 位要求导致 Apk 上传错误
- observable - 如何在特定队列上启动一系列可观察对象?
- python - Df到sql到python中的Teradata
- apollo-server - 如何在没有 Apollo Server 但使用 express-graphql 的情况下使用 apollo-datasource-rest
- angular - 自定义单元格组件的 AgGrid 行 autoHeight
- jenkins - Jenkins 声明式管道:如何重命名“声明式:发布操作”步骤?
- python - 计算 Python 中的事件数
- python - 有没有办法在 Flask-RESTPlus 中显示长字段描述,并在文本框中使用缩短的文本