欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

比较mutex.lock和mutex.try_lock的功能差异:一场解锁操作的实验探究

最编程 2024-07-28 18:54:03
...

关于try_lock()

1.如果互斥锁当前未被任何线程锁定,则调用线程将其锁定(从此点开始,直到调用其成员解锁,该线程拥有互斥锁)。
2.如果互斥锁当前被另一个线程锁定,则该函数将失败并返回false,而不会阻塞(调用线程继续执行)。
3.如果互斥锁当前被调用此函数的同一线程锁定,则会产生死锁(具有未定义的行为)。 请参阅recursive_mutex以获取允许来自同一线程的多个锁的互斥锁类型。

volatile:修饰变量,此变量可能被多线程访问和修改,加上此关键字,可以避免编译器优化,不使用存储在寄存器中的值,而是每次都去内存里去读。

std::mutex mtx;
volatile int counter;
static void attempt_10k_increases()
{ 
	for (int i = 0; i<10000; ++i) 
	{
		if (mtx.try_lock())
		{
			++counter;
			mtx.unlock(); 
		} 
        //mtx.lock();
        //++counter;
		//mtx.unlock(); 
	}
}
int test_mutex_3()
{
	std::thread threads[10];
 	for (int i = 0; i<10; ++i)
		threads[i] = std::thread(attempt_10k_increases);
	for (auto& th : threads) 
		th.join();
	std::cout << counter << "successful increases of the counter.\n";
	return 0;
}
int main() 
{
	test_mutex_3();
	getchar();
	return 0;
}

经过多次运行,可以发现counter的值基本集中在3W多,4W多,5W多,而如果不用try_lock(),使用lock(),counter的值一定是100000。