请问,有人可以解释如何在c ++中使用和创建unique_lock吗? 它应该用于互斥监视器的任何过程,并能够对条件变量执行wait()...我不是从文档中了解我应该如何创建它。是必要的互斥?这是一个伪代码:
/* compile with g++, flags -std=c++0x -lpthread */
#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <string.h>
#include <unistd.h>
class monitorTh {
private:
std::mutex m;
std::condition_variable waitP;
std::condition_variable waitC;
char element[32];
std::unique_lock::unique_lock l;
public:
void produce(char* elemProd) {
l.lock();
if (/*already_present_element*/) {
waitP.wait(l);
}
else {/*produce element*/}
l.unlock();
}
void consume() {
/*something specular*/
}
};
int main(int argc, char* argv[]) {
monitorTh* monitor = new monitorTh();
char prodotto[32] = "oggetto";
std::thread producer([&]() {
monitor->produce(prodotto);
});
std::thread consumer([&]() {
monitor->consume();
});
producer.join();
consumer.join();
}
答案 0 :(得分:36)
std::unique_lock
使用RAII模式。
如果要锁定互斥锁,可以创建类型为std::unique_lock
的局部变量,并将互斥锁作为参数传递。当构造unique_lock时,它将锁定互斥锁,并且它将被破坏,它将解锁互斥锁。更重要的是:如果抛出异常,则会调用std::unique_lock
析构函数 ,因此将解锁互斥锁。
示例:
#include<mutex>
int some_shared_var=0;
int func() {
int a = 3;
{ //Critical section
std::unique_lock<std::mutex> lock(my_mutex);
some_shared_var += a;
} //End of critical section
}
答案 1 :(得分:6)
std::unique_lock<std::mutex>
持有对单独的std::mutex
对象的锁定。通过在构造函数中传递锁对象,可以将锁对象与互斥锁相关联。除非您另行指定,否则将立即锁定互斥锁。如果锁定对象在销毁时保持锁定,那么析构函数将释放锁定。通常,std::unique_lock<std::mutex>
对象将是一个局部变量,在您希望获取锁定的位置声明。
在您的情况下,produce()
函数可以这样写:
void produce(char* elemProd) {
std::unique_lock<std::mutex> lk(m); // lock the mutex
while (/*already_present_element*/) { // condition variable waits may wake spuriously
waitP.wait(lk);
}
{/*produce element*/}
// lk releases the lock when it is destroyed
}
请注意,我已将if
替换为while
,以说明来自wait()
来电的虚假提醒。
答案 2 :(得分:6)
使用条件变量的更详细的示例代码:
#include<mutex>
std::mutex(mu); //Global variable or place within class
std::condition_variable condition; //A signal that can be used to communicate between functions
auto MyFunction()->void
{
std::unique_lock<mutex> lock(mu);
//Do Stuff
lock.unlock(); //Unlock the mutex
condition.notify_one(); //Notify MyOtherFunction that this is done
}
auto MyOtherFunction()->void
{
std::unique_lock<mutex> lock(mu);
condition.wait(lock) //Wait for MyFunction to finish, a lambda can be passed also to protects against spurious wake up e.g (lock,[](){return *some condition*})
lock.unlock();
}
答案 3 :(得分:-5)
在这种情况下,我认为你需要做的就是:
m.lock();
// Critical section code
m.unlock();