我如何用升压临界区? [英] How do I make a critical section with Boost?

查看:114
本文介绍了我如何用升压临界区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关我的跨平台应用程序,我已经开始使用升压,但我不明白我怎么能实现code重现的Win32的临界区或.Net的锁定

我想写的方法,可以从不同的线程调用,以控制写操作共享领域。在同一个线程中的递归调用应该被允许(美孚() - >美孚())。

在C#这个实现是非常简单的:

 对象_synch =新的对象();
无效美孚()
{
    锁定(_synch)//一个线程不能由他自锁,但另一个线程必须等待,直到
    {
        //做一些工作
        如果(...)
        {
           美孚();
        }
    }
}


解决方案

通过提升你可以使用boost :: lock_guard<>类:

 类测试
{
上市:
 无效TestMethod的()
 {
  //这部分没有被锁定
  {
   提高:: lock_guard<提高:: recursive_mutex>锁定(m_guard);
   //这部分被锁定
  }
  //这部分没有被锁定
 }
私人的:
    提高:: recursive_mutex m_guard;
};

PS这些类位于 Boost.Thread 库。

For my cross-platform application I have started to use Boost, but I can't understand how I can implement code to reproduce behavior of Win32's critical section or .Net's lock.

I want to write a method Foo that can be called from different threads to control write operations to shared fields. Recursive calls within the same thread should be allowed (Foo() -> Foo()).

In C# this implementation is very simple:

object _synch = new object();
void Foo()
{
    lock (_synch)  // one thread can't be lock by him self, but another threads must wait untill
    {
        // do some works
        if (...) 
        {
           Foo();
        }
    }
}

解决方案

With boost you can use boost::lock_guard<> class:

class test
{
public:
 void testMethod()
 {
  // this section is not locked
  {
   boost::lock_guard<boost::recursive_mutex> lock(m_guard);
   // this section is locked
  }
  // this section is not locked
 }
private:
    boost::recursive_mutex m_guard;
};

PS These classes located in Boost.Thread library.

这篇关于我如何用升压临界区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆