zoukankan      html  css  js  c++  java
  • vc6线程同步

    #include <windows.h>
    #include <iostream>
    using namespace std;
    
    // HANDLE CreateThread(
    // 	LPSECURITY_ATTRIBUTES lpThreadAttributes,  // pointer to security attributes
    // 	DWORD dwStackSize,                         // initial thread stack size
    // 	LPTHREAD_START_ROUTINE lpStartAddress,     // pointer to thread function
    // 	LPVOID lpParameter,                        // argument for new thread
    // 	DWORD dwCreationFlags,                     // creation flags
    // 	LPDWORD lpThreadId                         // pointer to receive thread ID
    // );
    
    DWORD WINAPI ThreadProc1(
    	LPVOID lpParameter   // thread data
    );
    DWORD WINAPI ThreadProc2(
    	LPVOID lpParameter   // thread data
    );
    
    //int index=0;
    int tickets=100;
    HANDLE hMutex;
    int main(){
    	hMutex=CreateMutex(NULL,TRUE,"tickets");
    	if(hMutex){
    		if(ERROR_ALREADY_EXISTS == GetLastError()){
    			cout<<"已经有一个实例在运行"<<endl;
    			getchar();
    			return 0;
    		}
    	}
    	WaitForSingleObject(hMutex,INFINITE);
    	ReleaseMutex(hMutex);
    	ReleaseMutex(hMutex);
    	//Thread1
    	HANDLE hThread1;
    	//CREATE_SUSPENDED意为创建时挂起,等待唤醒 ResumeThread()
    	//0				  意为创建后立即执行
    	//hThread1 = CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);	
    	hThread1 = CreateThread(NULL,0,ThreadProc1,NULL,CREATE_SUSPENDED ,NULL);	
    	
    	//Thread2
    	HANDLE hThread2;
    	//hThread2 = CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
    	hThread2 = CreateThread(NULL,0,ThreadProc2,NULL,CREATE_SUSPENDED ,NULL);
    	ResumeThread(hThread1);
    	ResumeThread(hThread2);
    
    	while(tickets>0){	//票没有卖完
    		Sleep(10);
    	}
    	CloseHandle(hThread1);
    	CloseHandle(hThread2);
    	cout<<"main exit."<<endl;
    	/*while(index++<1000){
    		cout<<index<<"main is running"<<endl;
    		Sleep(5);
    	}*/
    	//Sleep(10);
    	getchar();
    	return 0;
    }
    DWORD WINAPI ThreadProc1(LPVOID lpParameter){
    	while(tickets>0){		
    		WaitForSingleObject(hMutex,INFINITE);
    		if(tickets>0){
    			Sleep(5);
    			cout<<"thread1 sells :"<<tickets -- <<endl;
    		}
    		ReleaseMutex(hMutex);
    	}	
    	return 0;
    }
    
    DWORD WINAPI ThreadProc2(LPVOID lpParameter){
    	while(tickets>0){
    		WaitForSingleObject(hMutex,INFINITE);
    		if(tickets>0){
    			Sleep(1);
    			cout<<"thread2 sells :"<< tickets -- <<endl;
    		}
    		ReleaseMutex(hMutex);
    	}	
    	return 0;
    }
    
    

  • 相关阅读:
    转载Crazybingo的文章: 第三章 创造平台——Quartus II 11.0 套件安装指南
    Can't launch the ModelSim-Altera software
    一种简单的ADV7842调试视频pixel_cnt/line的办法.
    调试ADV7842的点滴 之 hdmi
    沿检测使能,时钟同步化
    global clock network
    捡到篮子里边的都是菜
    (转)时序分析基本公式
    Spring中的AOP(一)
    AOP的概念
  • 原文地址:https://www.cnblogs.com/wucg/p/1949979.html
Copyright © 2011-2022 走看看