CRITICAL_SECTION 学习

简介:
// Critsetion.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <process.h>
using  namespace  std;
 
 
CRITICAL_SECTION g_cs;
char  name[]= "zhangdongsheng" ;
 
unsigned __stdcall ThreadPoc1( void * pArguments)
{
     while  (1)
     {
         EnterCriticalSection(&g_cs); //如果此处不对全局变量name进行加锁
                                      //那么输出结果将有可能出现不一致现象
         memset (name,0, sizeof (name));
         strcpy (name, "Thread1" );
         Sleep(600);
         cout<< "Thread1 " <<name<<endl;
         LeaveCriticalSection(&g_cs);
     }
 
     return  0;
}
unsigned __stdcall ThreadPoc2( void * pArguments)
{
     while (1)
     {
         EnterCriticalSection(&g_cs);
         memset (name,0, sizeof (name));
         strcpy (name, "Thread2" );
         Sleep(500);
         cout<< "Thread2 " <<name<<endl;
         LeaveCriticalSection(&g_cs);
     }
 
     return  0;
}
int  _tmain( int  argc, _TCHAR* argv[])
{
     InitializeCriticalSection(&g_cs);
     HANDLE  hThread1=( HANDLE )_beginthreadex(NULL,0,ThreadPoc1,NULL,0,NULL);
     HANDLE  hThread2=( HANDLE )_beginthreadex(NULL,0,ThreadPoc2,NULL,0,NULL);
     CloseHandle(hThread1);
     CloseHandle(hThread2);
     while (1)
     {
         Sleep(500);
     }
     DeleteCriticalSection(&g_cs);
     return  0;
}

不加锁会出现不一致的情况

加锁后:

相关文章
|
4月前
|
JavaScript
Uncaught runtime errors: × ERROR Avoided redundant navigation to current location: “/xxx“.
Uncaught runtime errors: × ERROR Avoided redundant navigation to current location: “/xxx“.
60 0
|
4月前
|
Rust 小程序
小程序警告:Now you can provide attr wxkey for a wxfor to improve performance
首先,无论什么程序,控制台中的警告都是会影响程序性能的。我们需要减少此类警告的出现,以提高程序的运行性能。 小程序开发的时候,遇到了如下的警告:
79 0
|
8月前
|
安全 Windows
CRITICAL_PROCESS_DIED
CRITICAL_PROCESS_DIED
921 2
relocation R_X86_64_PC32 against symbol can not be used when making a shared object recompile with
relocation R_X86_64_PC32 against symbol can not be used when making a shared object recompile with
419 0
relocation R_X86_64_PC32 against symbol lua_newstate can not be used when making a shared object
relocation R_X86_64_PC32 against symbol lua_newstate can not be used when making a shared object
201 0
PAT (Advanced Level) Practice - 1014 Waiting in Line(30 分)
PAT (Advanced Level) Practice - 1014 Waiting in Line(30 分)
95 0
PAT (Advanced Level) Practice - 1139 First Contact(30 分)
PAT (Advanced Level) Practice - 1139 First Contact(30 分)
93 0
PAT (Advanced Level) Practice - 1122 Hamiltonian Cycle(25 分)
PAT (Advanced Level) Practice - 1122 Hamiltonian Cycle(25 分)
94 0
|
JavaScript
SAP PP使用ECR去修改Recipe主数据,报错:Generation not supported for change object
SAP PP使用ECR去修改Recipe主数据,报错:Generation not supported for change object
SAP PP使用ECR去修改Recipe主数据,报错:Generation not supported for change object
|
NoSQL Redis

热门文章

最新文章