码迷,mamicode.com
首页 > 编程语言 > 详细

37 windows_37_Thread_InterLock 线程-原子锁

时间:2016-06-10 17:55:12      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

windows_37_Thread_InterLock 线程-原子锁

  1. // windows_37_Thread_InterLock.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include "windows.h"
  5. long g_nValue1 = 0;
  6. long g_nValue2 = 0;
  7. DWORD WINAPI InterProc1( LPVOID pParam )
  8. {
  9. for (int nIndex = 0; nIndex < 10000000;nIndex++)
  10. {
  11. //普通的加加
  12. g_nValue1++;
  13. }
  14. return 0;
  15. }
  16. DWORD WINAPI InterProc2( LPVOID pParam )
  17. {
  18. for (int nIndex = 0; nIndex < 100;nIndex++)
  19. {
  20. //原子锁加加
  21. //g_nValue2++;
  22. InterlockedIncrement( &g_nValue2 );
  23. }
  24. return 0;
  25. }
  26. void Create( )
  27. {
  28. DWORD nThreadID = 0;
  29. HANDLE hThread[4] = { NULL };
  30. hThread[0] = CreateThread( NULL, 0, InterProc1, NULL, 0, &nThreadID );
  31. hThread[1] = CreateThread( NULL, 0, InterProc1, NULL, 0, &nThreadID );
  32. hThread[2] = CreateThread( NULL, 0, InterProc2, NULL, 0, &nThreadID );
  33. hThread[3] = CreateThread( NULL, 0, InterProc2, NULL, 0, &nThreadID );
  34. WaitForMultipleObjects( 4, hThread, FALSE, INFINITE );
  35. printf( "%ld\n", g_nValue1 );
  36. printf( "%ld\n", g_nValue2 );
  37. }
  38. int _tmain(int argc, _TCHAR* argv[])
  39. {
  40. Create( );
  41. return 0;
  42. }





37 windows_37_Thread_InterLock 线程-原子锁

标签:

原文地址:http://www.cnblogs.com/nfking/p/5573918.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!