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;
    }
    
    

  • 相关阅读:
    Python pynput监听键盘
    ProceedingJoinPoint pjp 获取不到方法上
    springcloud- FeginClient 调用统一拦截添加请求头 RequestInterceptor ,被调用服务获取请求头
    多线程-Thread、Runnable 创建线程和调用过程分析
    spring --解析自定义注解SpringAOP(配合@Aspect)
    spring 核心接口之 Ordered
    图标文字
    文字展开和收起
    查找字符串中给定字符串的所有位置
    随机函数与JSON
  • 原文地址:https://www.cnblogs.com/wucg/p/1949979.html
Copyright © 2011-2022 走看看