gpt4 book ai didi

c++ - 交换互斥锁

转载 作者:搜寻专家 更新时间:2023-10-31 01:28:47 25 4
gpt4 key购买 nike

我在正确“交换”锁方面遇到了麻烦。考虑这种情况:

bool HidDevice::wait(const std::function<bool(const Info&)>& predicate)
{
/* A method scoped lock. */
std::unique_lock waitLock(this->waitMutex, std::defer_lock);

/* A scoped, general access, lock. */
{
std::lock_guard lock(this->mutex);

bool exitEarly = false;

/* do some checks... */

if (exitEarly)
return false;

/* Only one thread at a time can execute this method, however
other threads can execute other methods or abort this one. Thus,
general access mutex "this->mutex" should be unlocked (to allow threads
to call other methods) while at the same time, "this->waitMutex" should
be locked to prevent multiple executions of code below. */

waitLock.lock(); // How do I release "this->mutex" here?
}

/* do some stuff... */

/* The main problem is with this event based OS function. It can
only be called once with the data I provide, therefore I need to
have a 2 locks - one blocks multiple method calls (the usual stuff)
and "waitLock" makes sure that only one instance of "osBlockingFunction"
is ruinning at the time. Since this is a thread blocking function,
"this->mutex" must be unlocked at this point. */

bool result = osBlockingFunction(...);

/* In methods, such as "close", "this->waitMutex" and others are then used
to make sure that thread blocking methods have returned and I can safely
modify related data. */

/* do some more stuff... */

return result;
}

如何在不使代码过于复杂的情况下解决这个“交换”问题?我可以在锁定另一个之前解锁 this->mutex,但是我担心在那一纳秒内,可能会出现竞争条件。

编辑:

假设有 3 个线程正在调用 wait 方法。第一个将锁定 this->mutex,然后是 this->waitMutex,然后解锁 this->mutex。第二个将锁定 this->mutex 并且必须等待 this->waitMutex 可用。它不会解锁 this->mutex。第三个将卡在锁定 this->mutex 上。

我想让最后 2 个线程等待 this->waitMutex 可用。

编辑 2:

使用 osBlockingFunction 的扩展示例。

最佳答案

感觉设计/实现应该与 HidDevice::wait 上的 std::condition_variable cv 有点不同,并且只有一个互斥量。当你写“其他线程可以执行其他方法或中止这个方法”时,将调用 cv.notify_one 来“中止”这个等待。 cv.wait {enter wait & unlocks the mutex} atomically and on cv.notify {exits wait and locks the mutex} 原子性。这样 HidDevice::wait 就更简单了:

bool HidDevice::wait(const std::function<bool(const Info&)>& predicate)
{
std::unique_lock<std::mutex> lock(this->m_Mutex); // Only one mutex.

m_bEarlyExit = false;

this->cv.wait(lock, spurious wake-up check);

if (m_bEarlyExit) // A bool data-member for abort.
return;

/* do some stuff... */
}
  • 我的假设是(根据函数的名称)在 /* 上做一些检查... */ 线程等待直到某些逻辑成立。

“中止”等待,将由其他线程调用的其他 HidDevice 函数负责:

void HidDevice::do_some_checks() /* do some checks... */
{
if ( some checks )
{
if ( other checks )
m_bEarlyExit = true;

this->cv.notify_one();
}
}

类似的东西。

关于c++ - 交换互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352436/

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