• C++之线程信号量机制


    #include<iostream>
    #include<Windows.h>
    using namespace std;
    int tickets=100;         //火车票总数
    HANDLE hSemaphore;
    DWORD WINAPI Thread1Proc(LPVOID lpParameter);//进程函数
    DWORD WINAPI Thread2Proc(LPVOID lpParameter);//进程函数
    void main()
    {
    	HANDLE hThread1;
    	HANDLE hThread2;
    	hThread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL);   //创建线程
    	hThread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL);
    	hSemaphore=CreateSemaphore(NULL,1,1,NULL);      //创建信号量,初始为1,最多为1
    	CloseHandle(hThread1);       //释放句柄
    	CloseHandle(hThread2);
    	CloseHandle(hSemaphore);
    	while(TRUE)
    	{
    		WaitForSingleObject(hSemaphore,INFINITE);
    		if(tickets>0)
    		{
    			cout<<"主线程卖出第"<<tickets--<<"张票"<<endl;
    			Sleep(50);
    			ReleaseSemaphore(hSemaphore,1,NULL);
    		}
    		else
    		{
    			ReleaseSemaphore(hSemaphore,1,NULL);      //释放信号量资源
    			break;
    		}
    	}
    	ExitThread(0);
    }
    DWORD WINAPI Thread1Proc(LPVOID lpParameter)
    {
    	while(TRUE)
    	{
    		WaitForSingleObject(hSemaphore,INFINITE);//申请信号量
    	    if(tickets>0)
    	    {
    		   cout<<"线程一卖掉第"<<tickets--<<"张票"<<endl;
    		   Sleep(50);
    		   ReleaseSemaphore(hSemaphore,1,NULL);
    	    }
    	    else
    		{
    			ReleaseSemaphore(hSemaphore,1,NULL);
    			break;
    		}
    	}
    	return 0;
    }
    DWORD WINAPI Thread2Proc(LPVOID lpParameter)
    {
    	while(TRUE)
    	{
    		WaitForSingleObject(hSemaphore,INFINITE);
    		if(tickets>0)
    		{
    			cout<<"线程二卖出第"<<tickets--<<"张票"<<endl;
    			Sleep(50);
    			ReleaseSemaphore(hSemaphore,1,NULL);
    		}
    		else
    		{
    			ReleaseSemaphore(hSemaphore,1,NULL);
    			break;
    		}
    	}
    	return 0;
    }

  • 相关阅读:
    php的cURL库介绍
    php函数ob_start()、ob_end_clean()、ob_get_contents()
    php中curl、fsockopen的应用
    App架构设计经验谈:服务端接口的设计
    图解正向代理与反向代理
    三种数据库连接池的配置
    数据库连接池在Tomcat中的几种配置方法
    Java四种线程池的使用
    JVM调优总结(一)-- 一些概念
    JVM调优总结(十)-调优方法
  • 原文地址:https://www.cnblogs.com/zztong/p/6695215.html
Copyright © 2020-2023  润新知