如何解决条件变量自定义等待函数
我创建了自定义 SpinLock 类
error: no matching function for call to ‘std::condition_variable::wait(std::unique_lock<Spinlock>&)’
cv_.wait(lk);
我在第 cv_.wait(lk);
行出错
如何支持我的 SpinLock 条件变量?
我想声明我自己的函数 wait void wait(unique_lock<SpinLock>& __lock,_Predicate __p)
签名。
#include <atomic>
#include <iostream>
#include <string>
#include <cstdlib> // atoi
#include <thread> // thread
#include <mutex> // mutex
#include <condition_variable>
#include <vector>
using namespace std;
class Spinlock {
private:
std::atomic_flag lock_ = ATOMIC_FLAG_INIT;
public:
void lock()
{
while (lock_.test_and_set(std::memory_order_acquire)) continue;
}
void unlock()
{
lock_.clear(std::memory_order_release);
}
};
class PrintOrder final {
public:
PrintOrder(int n,int threadNum)
: maxnum_(n),curNum_(0)
{
startTime_ = chrono::steady_clock::Now();
threads_.reserve(threadNum);
unique_lock<Spinlock> lk(spinLock_);
for(int x = 0; x < threadNum; ++x)
{
threads_.emplace_back(&PrintOrder::background,this,x);
}
}
~PrintOrder() {
for(auto&& th : threads_)
{
th.join();
}
auto endTime = chrono::steady_clock::Now();
auto diff = endTime - startTime_;
cout << chrono::duration <double,milli> (diff).count() << " ms" << endl;
}
void background(int x) {
while(true) {
unique_lock<Spinlock> lk(spinLock_);
// wait until it's this thread's turn or curNum_ > maxnum_
while((curNum_ % threads_.size()) != x and curNum_ <= maxnum_)
{
cv_.wait(lk);
}
if(curNum_ > maxnum_)
{
break;
}
cout << curNum_ << endl;
++curNum_;
cv_.notify_all();
}
}
private:
int maxnum_;
int curNum_;
Spinlock spinLock_;
condition_variable cv_;
vector<thread> threads_;
chrono::time_point<chrono::steady_clock> startTime_;
};
int main(int argc,char **argv) {
if (argc == 3)
{
int maxnum = atoi(argv[1]);
int threadsNum = atoi(argv[2]);
PrintOrder printOrder(maxnum,threadsNum);
} else {
cout << "ERROR: expected console input: <maxnum> <threadsNum>" << endl;
}
return 0;
}
解决方法
std::condition_variable
仅支持 std::unique_lock<std::mutex>
。改用 std::condition_variable_any
。
condition_variable_any
类是 std::condition_variable
的泛化。 std::condition_variable
仅适用于 std::unique_lock<std::mutex>
,而 condition_variable_any
可以对满足 BasicLockable
要求的任何锁进行操作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。