编程还是得搞清楚操作系统的运行最重要,基础知识要打牢固。
#include <iostream>
#include <stdlib.h>
#include <Windows.h>
int ticke_number = 100; //定义100张票。
CRITICAL_SECTION cs; //定义全局临界区。
DWORD WINAPI ThreadFunc(LPVOID lpParameter) {
char* name = (char*)lpParameter;
while (true)
{
if (ticke_number <= 0) {
printf("%s ============票卖完了==========\n", name);
break;
}
EnterCriticalSection(&cs);
if (ticke_number >0) {
printf("%s 开始卖第 %d 张票了\n", name, ticke_number);
ticke_number--;
}
LeaveCriticalSection(&cs);
int x = rand() % 1000;
Sleep(x);
}
return 0;
}
int main() {
InitializeCriticalSection(&cs); //初始化临界区
//A,B,C开始卖票。
HANDLE threadHandle1 = CreateThread(NULL, 0, ThreadFunc, (LPVOID)"A", 0, NULL);
HANDLE threadHandle2 = CreateThread(NULL, 0, ThreadFunc, (LPVOID)"B", 0, NULL);
HANDLE threadHandle3 = CreateThread(NULL, 0, ThreadFunc, (LPVOID)"C", 0, NULL);
if (threadHandle1 == NULL || threadHandle2==NULL || threadHandle3==NULL) {
perror("CreateThread error");
return -1;
}
HANDLE lpHandles[] = {threadHandle1,threadHandle2,threadHandle3};
WaitForMultipleObjects(3, lpHandles,TRUE,INFINITE); //等待所有的票卖完。
DeleteCriticalSection(&cs); //删除临界区
CloseHandle(threadHandle1);
CloseHandle(threadHandle2);
CloseHandle(threadHandle3);
printf("主线程执行完毕");
return 0;
}