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

 

posted @ 2011-02-08 21:20  庚武  Views(376)  Comments(0Edit  收藏  举报