std mutex 以某种方式允许两个线程执行

问题描述 投票:0回答:0

我正在调试一个类函数。我认为问题可能是两个线程之间的竞争条件,所以我添加了一个互斥锁以确保调试时的独占访问。

我正在记录线程 ID 以及线程何时进入/退出块:

class C
{
public:

    __attribute__((always_inline)) RetType f()
    {
        RetType ret;

        {
            std::scoped_lock<std::mutex> lock(mutex_);
        
            std::cout << "tid (" << getThreadId() << ") START" << std::endl << std::flush;
            ret = func();
            std::cout << "tid (" << getThreadId() << ") FINISH" << std::endl << std::flush;
        }

        return ret;
    }

    static inline size_t getThreadId()
    {
        return std::hash<std::thread::id>{}(std::this_thread::get_id());
    }

private:
    static inline std::mutex mutex_;
};

问题是日志记录显示第二个线程在第一个线程完成之前进入块:

tid (11174764178590795234) START
tid (14199924658679700966) START       This shouldn't happen until thread 234 FINISHes
tid (11174764178590795234) FINISH
tid (11174764178590795234) START
tid (11174764178590795234) FINISH
tid (11174764178590795234) START
tid (11174764178590795234) FINISH
tid (11174764178590795234) START
tid (11174764178590795234) FINISH
tid (11174764178590795234) START
tid (11174764178590795234) FINISH
tid (11174764178590795234) START
tid (11174764178590795234) FINISH
tid (11174764178590795234) START
tid (11174764178590795234) FINISH
tid (11174764178590795234) START
tid (14199924658679700966) FINISH
tid (14199924658679700966) START

这应该不可能吧?我做错了什么?

c++ multithreading thread-safety mutex
© www.soinside.com 2019 - 2024. All rights reserved.