您当前的位置: 首页 > 

龚建波

暂无认证

  • 2浏览

    0关注

    313博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

测试 std::mutex && CRITICAL_SECTION && QMutex 三者的效率

龚建波 发布时间:2020-09-01 15:23:52 ,浏览量:2

std::mutex 标准库的互斥锁;CRITICAL_SECTION Windows提供的临界区;QMutex Qt提供的互斥锁封装,显然,Qt封装的效率一般不如前两者。

参照这篇文章:https://www.iteye.com/blog/aigo-1908084

和他的结论差不多:在旧版本编译器上(如VS2012/2013),std::mutex 比临界区更慢;在新版本编译器上(如VS2015/2017),std::mutex 的效率显著提高,特别在竞争情况下比临界区快多了。

下面是 VS2013 和 VS2017 的运行截图(x86 Release):

测试代码两份:

#include 
#include 
#include   
#include     
#include   
#include   
#include 
#include   

//表示被锁定的资源,每次加1  
long total = 0;

//win临界区
//Windows下的Mutex和​CRITICAL_SECTION,都是递归锁,
//而Linux下的pthread_mutex,默认是非递归锁
CRITICAL_SECTION critical;
//互斥锁
std::mutex mtx;
//可递归互斥锁
std::recursive_mutex r_mtx;

void run_critical(int count)
{
	for (int i = 0; i < count; ++i)
	{
		EnterCriticalSection(&critical);
		++total;
		LeaveCriticalSection(&critical);
	}
}

void run_mutex(int count)
{
	for (int i = 0; i < count; ++i)
	{
		//std::lock_guard guard(mtx);
		mtx.lock();
		++total;
		mtx.unlock();
	}
}

void run_recursive_mutex(int count)
{
	for (int i = 0; i < count; ++i)
	{
		//std::lock_guard guard(r_mtx);
		r_mtx.lock();
		++total;
		r_mtx.unlock();
	}
}

void run_test(std::function func, int thread_count, const char * type)
{
	std::list threadlist;

	total = 0;
	clock_t start = clock();
	for (int i = 0; i < thread_count; ++i)
	{
		std::thread *t1 = new std::thread(func);
		threadlist.push_back(t1);
	}
	for (std::list::const_iterator i = threadlist.begin(); i != threadlist.end(); i++)
	{
		(*i)->join();
	}
	clock_t finish = clock();
	std::cout             
关注
打赏
1655829268
查看更多评论
0.1274s