zoukankan      html  css  js  c++  java
  • CriticalSection关键代码区(临界区)

    #include <windows.h>
    #include <iostream>
    using namespace std;
    
    DWORD WINAPI MyThreadProc1(LPVOID lpParameter);		//thread data
    DWORD WINAPI MyThreadProc2(LPVOID lpParameter);
    
    int tickets=100;
    
    CRITICAL_SECTION g_cs;
    
    int main(){
    
    	DWORD tid1=0,tid2=0;
    
    	HANDLE handle1 = CreateThread(NULL,0,MyThreadProc1,NULL,CREATE_SUSPENDED ,&tid1);		
    	HANDLE handle2 = CreateThread(NULL,0,MyThreadProc2,NULL,CREATE_SUSPENDED ,&tid2);
    
    	ResumeThread(handle1);	
    	ResumeThread(handle2);	
    
    	InitializeCriticalSection(&g_cs);
    
    	Sleep(5000);
    
    	DeleteCriticalSection(&g_cs);
    
    	CloseHandle(handle1);
    	CloseHandle(handle2);
    
    	cout<< "SubThread1 ID:" << hex << uppercase<< tid1 << endl;
    	cout<< "SubThread2 ID:" << hex << uppercase<< tid2 << endl;
    	
    	system("pause");
    	return 0;
    }
    
    DWORD WINAPI MyThreadProc1(LPVOID lpParameter )
    {	
    	while(TRUE){		
    		EnterCriticalSection(&g_cs);
    		if(tickets){
    			cout<<"子线程1卖票:"<<tickets<<endl;
    			--tickets;
    			Sleep(15);			
    			LeaveCriticalSection(&g_cs);
    		}
    		else
    		{
    			LeaveCriticalSection(&g_cs);
    			break;
    		}		
    	}
    	return 1;
    }
    
    
    
    DWORD WINAPI MyThreadProc2(LPVOID lpParameter)
    {
    	while(TRUE){
    		EnterCriticalSection(&g_cs);
    		if(tickets){
    			cout<<"子线程2卖票:"<<tickets<<endl;
    			--tickets;
    			Sleep(15);
    			LeaveCriticalSection(&g_cs);
    		}
    		else
    		{
    			LeaveCriticalSection(&g_cs);
    			break;
    		}
    	}		
    	return 1;
    }
    

      

  • 相关阅读:
    PostgreSQL 模式(SCHEMA)
    PostgreSQL学习---模式schema
    psql 工具详细使用介绍
    CentOS 下 VNC Server 的配置与使用
    如何处理/boot/efi/EFI/cento from install of fwupdate-efi
    uGUI练习(二) Animate UI
    uGUI练习(一) Anchor
    uGUI练习 开篇
    Fix "Missing Scripts"
    用uGUI开发自定义Toggle Slider控件
  • 原文地址:https://www.cnblogs.com/wucg/p/2415563.html
Copyright © 2011-2022 走看看