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

  • 相关阅读:
    图片上传 多张
    ES6的新特性
    css超出一行添加省略号属性:text-overflow和white-space
    JQuery 中 is(':visible') 解析及用法
    Git详解之Git分支
    jQuery选择器和选取方法
    git命令之git remote的用法
    运算符中的一些小技巧
    Git 忽略一些文件不加入版本控制
    git 查看远程分支、本地分支、创建分支、把分支推到远程repository、删除本地分支
  • 原文地址:https://www.cnblogs.com/wucg/p/1949979.html
Copyright © 2020-2023  润新知