多线程锁竞争造成的开销
2014-04-18 12:03
155 查看
这是执行结果先看实例代码:#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,好调试。
相关文章推荐
- Java 多线程 竞争造成的异常
- java多线程竞争
- 多线程与托管以及堆栈共同作用造成的内存问题
- (NIO)有效解决了多线程服务器存在的线程开销
- 多线程的开销与好处
- 利用jdk自带的强悍工具jvisualvm检测多线程的竞争
- 高通dsp多线程造成系统挂掉笔记
- 对多线程对订单更新竞争的锁机制的实现-初构
- 好记性不如烂笔头75-多线程-并行访问下的资源竞争和样例
- VC6下深入理解new[]和delete[](在多线程下new和delete的时候,必须选择上多线程库,不然可能造成进程崩溃)
- java多线程(二)解决共享资源竞争
- 关于多线程操作同步对象造成死锁的解决方式(一)
- 多线程修改VCL控件造成的ntdll.dll错
- JAVA--多线程中notify()造成的死锁原因的研究与使用
- 如何在中间件bug排查中画多线程竞争流程图
- 多线程造成死锁的例子
- C++11实现多线程 互斥锁与资源竞争问题
- 2017.2.22 多线程访问成员变量造成的问题及改正
- HashMap在多线程环境下偶然造成InfiniteLoop导致程序宕机
- 多线程编程的锁问题解析(锁竞争死锁活锁及Date Race等)