zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    爬虫入门---Python2和Python3的不同
    Python学习笔记——文件
    Python字典笔记
    Python列表操作——模拟实现栈和队列
    元组的cmp()内建函数
    Unicode基本概念
    神经网络基本的一些概念
    LLDB调试基本使用
    HTML实现跳转到页面指定位置
    通过pod导入第三方框架
  • 原文地址:https://www.cnblogs.com/zztong/p/6695215.html
Copyright © 2011-2022 走看看