• 线程同步之生产者与消费者问题


    转载自:http://blog.csdn.net/morewindows/article/details/7577591

    代码:

    #include <process.h>
    #include <Windows.h>
    #include <iostream>
    using namespace std;
    
    CRITICAL_SECTION g_cs;
    
    HANDLE g_hPoolEmpty, g_hPoolFull;
    int g_nNumProduct;//表示缓存区的产品数量
    
    UINT WINAPI Product(PVOID pNum)
    {
    	WaitForSingleObject(g_hPoolEmpty, INFINITE); //当获得信号量时,信号量的计数减1,表示有一个线程使用信号量。当有空的时间,就可以生产了
    	ReleaseSemaphore(g_hPoolFull, 1, NULL);      //信号量的计数加1,此时释放是为了让其它线程可以运行
    
    	EnterCriticalSection(&g_cs);
    	g_nNumProduct++;
    	cout << "产生1个后的数量为 :" << g_nNumProduct << endl;
    	LeaveCriticalSection(&g_cs);
    
    	return 0;
    }
    
    UINT WINAPI Customer(PVOID pNum)
    {
    	WaitForSingleObject(g_hPoolFull, INFINITE);//当有东西的时候,才可以消费,记住当g_hPoolFull为0时,就为不触发状态,就不能获得信号
    	ReleaseSemaphore(g_hPoolEmpty, 1, NULL);
    
    	EnterCriticalSection(&g_cs);
    	g_nNumProduct--;
    	cout << "消费1个后的数量为 :" << g_nNumProduct << endl;
    	LeaveCriticalSection(&g_cs);
    	return 0;
    }
    
    void main()
    {
    	g_hPoolEmpty = CreateSemaphore(NULL, 10, 10, NULL);//表示有10个空的资源等着被使用,触发状态
    	g_hPoolFull  = CreateSemaphore(NULL, 0, 10, NULL);//表示当前有0个资源等着被使用,示触发状态
    	InitializeCriticalSection(&g_cs);
    	g_nNumProduct = 0;
    
    	HANDLE hThread[8];
    
    	int i;
    	for (i = 0; i < 5; i++)
    	{
    		hThread[i] = (HANDLE)_beginthreadex(NULL, 0, Product, NULL, 0, NULL);
    	}
    
    	for (i = 5; i < 8; i++)
    	{
    		hThread[i] = (HWND)_beginthreadex(NULL, 0, Customer, NULL, 0, NULL);
    	}
    
    	WaitForMultipleObjects(8, hThread, TRUE, INFINITE);
    
    	CloseHandle(g_hPoolEmpty);
    	CloseHandle(g_hPoolFull);
    	DeleteCriticalSection(&g_cs);
    }
    
  • 相关阅读:
    hdu-5112-A Curious Matt
    nyoj-47-过河问题|POJ-1700-Crossing River
    nyoj-914-Yougth的最大化
    nyoj-1103-区域赛系列一多边形划分
    nyoj-586-疯牛|poj-2456-Aggressive cows
    nyoj-248-buying feed
    nyoj-236-心急的C小加
    nyoj-14-会场安排问题
    Codeforces Round #277.5 (Div. 2)-D. Unbearable Controversy of Being
    Codeforces Round #277.5 (Div. 2)-C. Given Length and Sum of Digits...
  • 原文地址:https://www.cnblogs.com/wang-can/p/3335605.html
Copyright © 2020-2023  润新知