多线程锁竞争造成的开销

这是执行结果

先看实例代码:

#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 __stdcall thread2(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, "thread2 t2-t1=%ld", t2-t1);
	printf(buf);
	printf("\n");

	return 1;
}

int _tmain(int argc, _TCHAR* argv[])
{
	InitializeCriticalSection(&cs);
	clock_t t1,t2;
	t1 = clock();      
	for ( int i = 0; i < 10000000; i++ )    
	{          
		EnterCriticalSection(&cs);          
		LeaveCriticalSection(&cs);     
	}      
	t2 = clock();  
   
	char buf[100]={0};
	sprintf(buf, "main thread t2-t1=%ld", t2-t1);
	printf(buf);
	printf("\n");
	

	_beginthreadex(NULL, 0, thread1,NULL,0,NULL);
    _beginthreadex(NULL, 0,thread2,NULL,0,NULL);


	Sleep(100000);
 return 0;
}
 
 
上面的代码,愿意是想通过多核优势,分两个线程来计算主线程中的1000W次循环。理论上来说,thread1和thread2分别花费的时间应该是main thread的一半,结果分别是main thread的一倍还要多,原因就是:两个线程因为锁竞争成了串行化操作,没有充分利用多核优势,并且平凡的大量锁竞争和锁竞争在某些情况下造成的线程切换,使得时间倍增。所以,尽量减少线程,减少锁竞争,而且这样还少些BUG,好调试。
 
 



你可能感兴趣的:(操作系统)