两者都是加锁,但是lock()是以阻塞的形式,try_lock()则是以非阻塞的形式进行的。
举个例子:
#include <iostream>
#include <thread>
#include <mutex>
volatile int g_iCount(0);
mutex mtx;
void UseLock()
{
for (int i(0); i<10000; ++i)
{
mtx.lock();
++g_iCount;
mtx.unlock();
}
}
void UseTryLock()
{
for (int i(0); i<10000; ++i)
{
if (mtx.try_lock())
{
++g_iCount;
mtx.unlock();
}
}
}
int main(int argc, char *argv[])
{
thread ths1[10];
for (int i(0); i<10; ++i)
{
ths1[i] = thread(UseTryLock);
}
for (auto &th : ths1);
{
th.join();
}
cout << g_iCount << endl;
g_iCount = 0;
thread ths2[10];
for (int i(0); i<10; ++i)
{
ths2[i] = thread(UseLock);
}
for (auto & th : ths2)
{
th.join();
}
cout << g_iCount << endl;
return 0;
}
输出结果如下:
其中,UseTryLock函数的每次输出结果实际上基本上都不一样。
由此可见阻塞和非阻塞模式对于结果的影响还是比较大的。