首页 > 解决方案 > 这种基于线程 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
    }
    ...

我正在尝试寻求专家的建议:

这种方法是否有任何可能的弱点/缺陷或矫枉过正(也许我错过了一些更简单的解决方案)?

您会使用不同的“解决方案缓冲区”保护方法吗?

也许您会使用完全不同的并行化方案(这也值得知道)?

标签: c++multithreadingsynchronizationatomic

解决方案


您的解决方案应该按预期工作,但是,使用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来标识不同的线程。


推荐阅读