多线程锁竞争造成的开销

本文探讨了多线程环境下锁竞争对程序性能的影响。通过实例代码展示,详细解析了锁竞争可能导致的开销,包括上下文切换、等待时间及资源消耗等,并提出优化建议。
摘要由CSDN通过智能技术生成

这是执行结果

先看实例代码:

#include "stdafx.h"
#include <Windows.h>
#include <string>
#include <set>
#include <io.h>
#include <fstream>
#include <Windows.h>
#include<time.h>
#include <stdio.h>
#include <process.h>
using namespace  std;


CRITICAL_SECTION cs;
unsigned __stdcall thread1(LPVOID lpVoid)
{
	clock_t t1,t2;
	t1 = clock();      
	for ( int i = 0; i < 5000000; i++ )    
	{          
		EnterCriticalSection(&cs);          
		LeaveCriticalSection(&cs);     
	}      
	t2 = clock();  

	char buf[100]={0};
	sprintf(buf, "thread1 t2-t1=%ld", t2-t1);
	printf(buf);
	printf("\n");
	return 1;
}

unsigned __stdc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值