- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想编写一个自定义互斥锁,这样每个线程都可以提供一个参数来表示当前线程想要执行的操作的复杂性。如果操作的复杂度低,其他线程将像自旋锁一样进入循环,但如果操作的复杂度中等,每个线程将迭代 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/
我试图让我的 SCNNode 自动水平旋转。这是我到目前为止的代码: box.scale = SCNVector3(x: 0.26, y: 0.26, z: 0.26) box.position =
我试图让我的 SCNNode 自动水平旋转。这是我到目前为止的代码: box.scale = SCNVector3(x: 0.26, y: 0.26, z: 0.26) box.position =
我试图让 unicode 三 Angular 形 (▵) 在页面加载时和用户将鼠标悬停在跨度上时旋转 360 度。我已经设置了一个 jsFiddle解释我想要什么。 ULTR▵ 我对 CS
我是一名优秀的程序员,十分优秀!