4

我正在尝试解决 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 - 所以我想知道它是否真的有效。

问候,保罗

4

1 回答 1

7

对我来说,它似乎正在工作,除了作用域锁不是 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
于 2012-04-16T14:08:48.507 回答