スコープロックが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