使用try_lock增强锁定

时间:2012-04-16 10:12:52

标签: c++ multithreading boost locking

我正试图解决Boost 1.46.1的锁定问题 - 我尝试了一些事情,但我感到不快乐 - 所以我很乐意听到干净利落的输入。

主题A:

  • 必须始终等待并获取关键数据部分的锁定
  • 更新一些关键数据
  • 手动解锁(或作用域)

线程B. - 必须永远不会阻止(try_lock?) - 如果获得锁定,则从上述关键部分读取数据

我不确定我是否需要shared_lock,或者我是否可以解决此问题。

编辑,我的代码如下: 线程A:

{
 // Critical section
 boost::mutex::scoped_lock  lock( _mutex) ;
}

主题B:

boost::mutex::scoped_lock lock(_mutex, boost::try_to_lock);
if( lock ) {

}

但是我无法记录失败的try_lock - 所以我想知道它是否真的有效。

此致 保罗

1 个答案:

答案 0 :(得分:6)

对我而言似乎它正在工作,除了范围锁不是FIFO,即请求锁的第一个线程,不是第一个获得锁的线程。我使用以下代码进行测试:

#include <boost/thread.hpp>
#include <cstdio>

boost::mutex mutex;

void threadA()
{
    for (int i = 10; i > 0; )
    {
        boost::mutex::scoped_lock lock(mutex);
        {
            fprintf(stderr, "Locked by A\n");
            usleep(100000);
            fprintf(stderr, "Unlocked by A\n");
            i--;
        }
    }
}

void threadB()
{
    for (int i = 10; i > 0; )
    {
        boost::mutex::scoped_lock lock(mutex, boost::try_to_lock);
        if (lock)
        {
            fprintf(stderr, "Locked by B\n");
            usleep(100000);
            fprintf(stderr, "Unlocked by B\n");
            i--;
        }
        else
        {
            fprintf(stderr, "Lock failed in B\n");
            usleep(100000);
        }
    }
}

int main(int argc, char **argv)
{
    boost::thread a(threadA);
    boost::thread b(threadB);
    a.join();
    b.join();
}

我得到了输出

Locked by A
Lock failed in B
Lock failed in B
Unlocked by A
Locked by A
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Lock failed in B
Unlocked by A
Locked by A
Unlocked by A
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B