gpt4 book ai didi

c++ - 让线程在自旋锁中休眠的方法

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

我想编写一个自定义互斥锁,这样每个线程都可以提供一个参数来表示当前线程想要执行的操作的复杂性。如果操作的复杂度低,其他线程将像自旋锁一样进入循环,但如果操作的复杂度中等,每个线程将迭代 50 次,然后根据条件变量休眠,如果操作非常复杂,其他线程将直接去 sleep 。

    enum LockOperation
{
LockOperation_Light = -1,
LockOperation_Medium = 50,
LockOperation_Heavy = 1
};

class CustomMutex
{
private:

protected:
std::atomic<int> mFlag;
std::mutex mMutex;
std::condition_variable mCond;

public:
CustomMutex() { std::atomic_init(&mFlag, 0); };
~CustomMutex() {};

void lock(LockOperation pLockOperation = LockOperation_Medium)
{
int lNewLoopCount = static_cast<int>(pLockOperation);
int lLoopCounter = 0;
int lExpected = 0;
int lLoopCount = std::atomic_load_explicit(&mFlag, std::memory_order_relaxed);

while (true)
{
while(std::atomic_load_explicit(&mFlag, std::memory_order_relaxed) != 0 &&
lLoopCounter != lLoopCount)
++lLoopCounter;
std::atomic_compare_exchange_strong_explicit(
&mFlag,
&lExpected,
lNewLoopCount,
std::memory_order_acquire,
std::memory_order_relaxed);
if(lExpected == 0)
{
return;
}
else if(lLoopCounter == lLoopCount)
{
lExpected = 0;
std::unique_lock<std::mutex> lGuard(mMutex);
mCond.wait(lGuard);
}
else
{
lExpected = 0;
continue;
}
}
};
bcInline void UnLock()
{
std::atomic_store_explicit(&mFlag, 0, std::memory_order_relaxed);
std::lock_guard<std::mutex> lGuard(mMutex);
mCond.notify_one();
};
};

现在假设线程 1 锁定了这个互斥体,线程 2 等待,因为它的 loopCounter 到达它的末尾,就在锁定条件变量的互斥体之前,线程 1 调用条件变量上的通知。现在 thread2 将休眠,直到另一个线程锁定此互斥量然后对其调用解锁。

我是多线程的新手,我想学习。我知道我的类可能包含错误或者可能完全错误,但是有什么方法可以纠正这个问题或者有什么好的算法来编写这样的互斥量。

另一个问题:我的原子操作顺序正确吗?

(对不起,如果我的问题有点模棱两可,我的英语不好)

最佳答案

我想如果我把 second if 改成这个:

else if(lLoopCounter == lLoopCount)
{
lExpected = 0;
std::unique_lock<std::mutex> lGuard(mMutex);
mCond.wait(
lGuard,
[&]()->bool { return std::atomic_load_explicit(&mFlag, std::memory_order_relaxed) == 0; });
}

然后解锁:

std::lock_guard<std::mutex> lGuard(mMutex);
std::atomic_store_explicit(&mFlag, 0, std::memory_order_relaxed);
mCond.notify_one();

问题会解决

现在为了优化,我可以从解锁方法中删除 lGuard 并将 std::memory_order_relaxed 更改为 std::memory_order_release 吗?(我怀疑是否为此发布新问题)

关于c++ - 让线程在自旋锁中休眠的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19160212/

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