原文地址:http://blog.csdn.net/morewindows/article/details/7577591
生产者消费者问题是一个著名的线程同步问题,该问题描述如下:有一个生产者在生产产品,这些产品将提供给若干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个具有多个缓冲区的缓冲池,生产者将它生产的产品放入一个缓冲区中,消费者可以从缓冲区中取走产品进行消费,显然生产者和消费者之间必须保持同步,即不允许消费者到一个空的缓冲区中取产品,也不允许生产者向一个已经放入产品的缓冲区中再次投放产品。
这个生产者消费者题目不仅常用于操作系统的课程设计,也常常在程序员和软件设计师考试中出现。并且在计算机考研的专业课考试中也是一个非常热门的问题。因此现在就针对这个问题进行详细深入的解答。
首先来简化问题,先假设生产者和消费者都只有一个,且缓冲区也只有一个。这样情况就简便多了。
第一.从缓冲区取出产品和向缓冲区投放产品必须是互斥进行的。可以用关键段和互斥量来完成。
第二.生产者要等待缓冲区为空,这样才可以投放产品,消费者要等待缓冲区不为空,这样才可以取出产品进行消费。并且由于有二个等待过程,所以要用二个事件或信号量来控制。
考虑这二点后,代码很容易写出来。另外为了美观起见,将消费者的输出颜色设置为彩色,有关如何在控制台下设置彩色输出请参阅《VC 控制台颜色设置》。
- //1生产者 1消费者 1缓冲区
- //使用二个事件,一个表示缓冲区空,一个表示缓冲区满。
- //再使用一个关键段来控制缓冲区的访问
- #include <stdio.h>
- #include <process.h>
- #include <windows.h>
- //设置控制台输出颜色
- BOOL SetConsoleColor(WORD wAttributes)
- {
- HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
- if (hConsole == INVALID_HANDLE_VALUE)
- return FALSE;
- return SetConsoleTextAttribute(hConsole, wAttributes);
- }
- const int END_PRODUCE_NUMBER = 10; //生产产品个数
- int g_Buffer; //缓冲区
- //事件与关键段
- CRITICAL_SECTION g_cs;
- HANDLE g_hEventBufferEmpty, g_hEventBufferFull;
- //生产者线程函数
- unsigned int __stdcall ProducerThreadFun(PVOID pM)
- {
- for (int i = 1; i <= END_PRODUCE_NUMBER; i++)
- {
- //等待缓冲区为空
- WaitForSingleObject(g_hEventBufferEmpty, INFINITE);
- //互斥的访问缓冲区
- EnterCriticalSection(&g_cs);
- g_Buffer = i;
- printf("生产者将数据%d放入缓冲区\n", i);
- LeaveCriticalSection(&g_cs);
- //通知缓冲区有新数据了
- SetEvent(g_hEventBufferFull);
- }
- return 0;
- }
- //消费者线程函数
- unsigned int __stdcall ConsumerThreadFun(PVOID pM)
- {
- volatile bool flag = true;
- while (flag)
- {
- //等待缓冲区中有数据
- WaitForSingleObject(g_hEventBufferFull, INFINITE);
- //互斥的访问缓冲区
- EnterCriticalSection(&g_cs);
- SetConsoleColor(FOREGROUND_GREEN);
- printf(" 消费者从缓冲区中取数据%d\n", g_Buffer);
- SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
- if (g_Buffer == END_PRODUCE_NUMBER)
- flag = false;
- LeaveCriticalSection(&g_cs);
- //通知缓冲区已为空
- SetEvent(g_hEventBufferEmpty);
- Sleep(10); //some other work should to do
- }
- return 0;
- }
- int main()
- {
- printf(" 生产者消费者问题 1生产者 1消费者 1缓冲区\n");
- printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
- InitializeCriticalSection(&g_cs);
- //创建二个自动复位事件,一个表示缓冲区是否为空,另一个表示缓冲区是否已经处理
- g_hEventBufferEmpty = CreateEvent(NULL, FALSE, TRUE, NULL);
- g_hEventBufferFull = CreateEvent(NULL, FALSE, FALSE, NULL);
- const int THREADNUM = 2;
- HANDLE hThread[THREADNUM];
- hThread[0] = (HANDLE)_beginthreadex(NULL, 0, ProducerThreadFun, NULL, 0, NULL);
- hThread[1] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
- WaitForMultipleObjects(THREADNUM, hThread, TRUE, INFINITE);
- CloseHandle(hThread[0]);
- CloseHandle(hThread[1]);
- //销毁事件和关键段
- CloseHandle(g_hEventBufferEmpty);
- CloseHandle(g_hEventBufferFull);
- DeleteCriticalSection(&g_cs);
- return 0;
- }
//1生产者 1消费者 1缓冲区
//使用二个事件,一个表示缓冲区空,一个表示缓冲区满。
//再使用一个关键段来控制缓冲区的访问
#include <stdio.h>
#include <process.h>
#include <windows.h>
//设置控制台输出颜色
BOOL SetConsoleColor(WORD wAttributes)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole == INVALID_HANDLE_VALUE)
return FALSE;
return SetConsoleTextAttribute(hConsole, wAttributes);
}
const int END_PRODUCE_NUMBER = 10; //生产产品个数
int g_Buffer; //缓冲区
//事件与关键段
CRITICAL_SECTION g_cs;
HANDLE g_hEventBufferEmpty, g_hEventBufferFull;
//生产者线程函数
unsigned int __stdcall ProducerThreadFun(PVOID pM)
{
for (int i = 1; i <= END_PRODUCE_NUMBER; i++)
{
//等待缓冲区为空
WaitForSingleObject(g_hEventBufferEmpty, INFINITE);
//互斥的访问缓冲区
EnterCriticalSection(&g_cs);
g_Buffer = i;
printf("生产者将数据%d放入缓冲区\n", i);
LeaveCriticalSection(&g_cs);
//通知缓冲区有新数据了
SetEvent(g_hEventBufferFull);
}
return 0;
}
//消费者线程函数
unsigned int __stdcall ConsumerThreadFun(PVOID pM)
{
volatile bool flag = true;
while (flag)
{
//等待缓冲区中有数据
WaitForSingleObject(g_hEventBufferFull, INFINITE);
//互斥的访问缓冲区
EnterCriticalSection(&g_cs);
SetConsoleColor(FOREGROUND_GREEN);
printf(" 消费者从缓冲区中取数据%d\n", g_Buffer);
SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
if (g_Buffer == END_PRODUCE_NUMBER)
flag = false;
LeaveCriticalSection(&g_cs);
//通知缓冲区已为空
SetEvent(g_hEventBufferEmpty);
Sleep(10); //some other work should to do
}
return 0;
}
int main()
{
printf(" 生产者消费者问题 1生产者 1消费者 1缓冲区\n");
printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
InitializeCriticalSection(&g_cs);
//创建二个自动复位事件,一个表示缓冲区是否为空,另一个表示缓冲区是否已经处理
g_hEventBufferEmpty = CreateEvent(NULL, FALSE, TRUE, NULL);
g_hEventBufferFull = CreateEvent(NULL, FALSE, FALSE, NULL);
const int THREADNUM = 2;
HANDLE hThread[THREADNUM];
hThread[0] = (HANDLE)_beginthreadex(NULL, 0, ProducerThreadFun, NULL, 0, NULL);
hThread[1] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
WaitForMultipleObjects(THREADNUM, hThread, TRUE, INFINITE);
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
//销毁事件和关键段
CloseHandle(g_hEventBufferEmpty);
CloseHandle(g_hEventBufferFull);
DeleteCriticalSection(&g_cs);
return 0;
}
运行结果如下所示:
可以看出生产者与消费者已经是有序的工作了。
然后再对这个简单生产者消费者问题加大难度。将消费者改成2个,缓冲池改成拥有4个缓冲区的大缓冲池。
如何来思考了这个问题了?首先根据上面分析的二点,可以知道生产者和消费者由一个变成多个的影响不大,唯一要注意的是缓冲池变大了,回顾一下《秒杀多线程第八篇 经典线程同步 信号量Semaphore》中的信号量,不难得出用二个信号量就可以解决这种缓冲池有多个缓冲区的情况——用一个信号量A来记录为空的缓冲区个数,另一个信号量B记录非空的缓冲区个数,然后生产者等待信号量A,消费者等待信号量B就可以了。因此可以仿照上面的代码来实现复杂生产者消费者问题,示例代码如下:
- //1生产者 2消费者 4缓冲区
- #include <stdio.h>
- #include <process.h>
- #include <windows.h>
- //设置控制台输出颜色
- BOOL SetConsoleColor(WORD wAttributes)
- {
- HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
- if (hConsole == INVALID_HANDLE_VALUE)
- return FALSE;
- return SetConsoleTextAttribute(hConsole, wAttributes);
- }
- const int END_PRODUCE_NUMBER = 8; //生产产品个数
- const int BUFFER_SIZE = 4; //缓冲区个数
- int g_Buffer[BUFFER_SIZE]; //缓冲池
- int g_i, g_j;
- //信号量与关键段
- CRITICAL_SECTION g_cs;
- HANDLE g_hSemaphoreBufferEmpty, g_hSemaphoreBufferFull;
- //生产者线程函数
- unsigned int __stdcall ProducerThreadFun(PVOID pM)
- {
- for (int i = 1; i <= END_PRODUCE_NUMBER; i++)
- {
- //等待有空的缓冲区出现
- WaitForSingleObject(g_hSemaphoreBufferEmpty, INFINITE);
- //互斥的访问缓冲区
- EnterCriticalSection(&g_cs);
- g_Buffer[g_i] = i;
- printf("生产者在缓冲池第%d个缓冲区中投放数据%d\n", g_i, g_Buffer[g_i]);
- g_i = (g_i + 1) % BUFFER_SIZE;
- LeaveCriticalSection(&g_cs);
- //通知消费者有新数据了
- ReleaseSemaphore(g_hSemaphoreBufferFull, 1, NULL);
- }
- printf("生产者完成任务,线程结束运行\n");
- return 0;
- }
- //消费者线程函数
- unsigned int __stdcall ConsumerThreadFun(PVOID pM)
- {
- while (true)
- {
- //等待非空的缓冲区出现
- WaitForSingleObject(g_hSemaphoreBufferFull, INFINITE);
- //互斥的访问缓冲区
- EnterCriticalSection(&g_cs);
- SetConsoleColor(FOREGROUND_GREEN);
- printf(" 编号为%d的消费者从缓冲池中第%d个缓冲区取出数据%d\n", GetCurrentThreadId(), g_j, g_Buffer[g_j]);
- SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
- if (g_Buffer[g_j] == END_PRODUCE_NUMBER)//结束标志
- {
- LeaveCriticalSection(&g_cs);
- //通知其它消费者有新数据了(结束标志)
- ReleaseSemaphore(g_hSemaphoreBufferFull, 1, NULL);
- break;
- }
- g_j = (g_j + 1) % BUFFER_SIZE;
- LeaveCriticalSection(&g_cs);
- Sleep(50); //some other work to do
- ReleaseSemaphore(g_hSemaphoreBufferEmpty, 1, NULL);
- }
- SetConsoleColor(FOREGROUND_GREEN);
- printf(" 编号为%d的消费者收到通知,线程结束运行\n", GetCurrentThreadId());
- SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
- return 0;
- }
- int main()
- {
- printf(" 生产者消费者问题 1生产者 2消费者 4缓冲区\n");
- printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
- InitializeCriticalSection(&g_cs);
- //初始化信号量,一个记录有产品的缓冲区个数,另一个记录空缓冲区个数.
- g_hSemaphoreBufferEmpty = CreateSemaphore(NULL, 4, 4, NULL);
- g_hSemaphoreBufferFull = CreateSemaphore(NULL, 0, 4, NULL);
- g_i = 0;
- g_j = 0;
- memset(g_Buffer, 0, sizeof(g_Buffer));
- const int THREADNUM = 3;
- HANDLE hThread[THREADNUM];
- //生产者线程
- hThread[0] = (HANDLE)_beginthreadex(NULL, 0, ProducerThreadFun, NULL, 0, NULL);
- //消费者线程
- hThread[1] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
- hThread[2] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
- WaitForMultipleObjects(THREADNUM, hThread, TRUE, INFINITE);
- for (int i = 0; i < THREADNUM; i++)
- CloseHandle(hThread[i]);
- //销毁信号量和关键段
- CloseHandle(g_hSemaphoreBufferEmpty);
- CloseHandle(g_hSemaphoreBufferFull);
- DeleteCriticalSection(&g_cs);
- return 0;
- }
//1生产者 2消费者 4缓冲区
#include <stdio.h>
#include <process.h>
#include <windows.h>
//设置控制台输出颜色
BOOL SetConsoleColor(WORD wAttributes)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole == INVALID_HANDLE_VALUE)
return FALSE;
return SetConsoleTextAttribute(hConsole, wAttributes);
}
const int END_PRODUCE_NUMBER = 8; //生产产品个数
const int BUFFER_SIZE = 4; //缓冲区个数
int g_Buffer[BUFFER_SIZE]; //缓冲池
int g_i, g_j;
//信号量与关键段
CRITICAL_SECTION g_cs;
HANDLE g_hSemaphoreBufferEmpty, g_hSemaphoreBufferFull;
//生产者线程函数
unsigned int __stdcall ProducerThreadFun(PVOID pM)
{
for (int i = 1; i <= END_PRODUCE_NUMBER; i++)
{
//等待有空的缓冲区出现
WaitForSingleObject(g_hSemaphoreBufferEmpty, INFINITE);
//互斥的访问缓冲区
EnterCriticalSection(&g_cs);
g_Buffer[g_i] = i;
printf("生产者在缓冲池第%d个缓冲区中投放数据%d\n", g_i, g_Buffer[g_i]);
g_i = (g_i + 1) % BUFFER_SIZE;
LeaveCriticalSection(&g_cs);
//通知消费者有新数据了
ReleaseSemaphore(g_hSemaphoreBufferFull, 1, NULL);
}
printf("生产者完成任务,线程结束运行\n");
return 0;
}
//消费者线程函数
unsigned int __stdcall ConsumerThreadFun(PVOID pM)
{
while (true)
{
//等待非空的缓冲区出现
WaitForSingleObject(g_hSemaphoreBufferFull, INFINITE);
//互斥的访问缓冲区
EnterCriticalSection(&g_cs);
SetConsoleColor(FOREGROUND_GREEN);
printf(" 编号为%d的消费者从缓冲池中第%d个缓冲区取出数据%d\n", GetCurrentThreadId(), g_j, g_Buffer[g_j]);
SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
if (g_Buffer[g_j] == END_PRODUCE_NUMBER)//结束标志
{
LeaveCriticalSection(&g_cs);
//通知其它消费者有新数据了(结束标志)
ReleaseSemaphore(g_hSemaphoreBufferFull, 1, NULL);
break;
}
g_j = (g_j + 1) % BUFFER_SIZE;
LeaveCriticalSection(&g_cs);
Sleep(50); //some other work to do
ReleaseSemaphore(g_hSemaphoreBufferEmpty, 1, NULL);
}
SetConsoleColor(FOREGROUND_GREEN);
printf(" 编号为%d的消费者收到通知,线程结束运行\n", GetCurrentThreadId());
SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
return 0;
}
int main()
{
printf(" 生产者消费者问题 1生产者 2消费者 4缓冲区\n");
printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
InitializeCriticalSection(&g_cs);
//初始化信号量,一个记录有产品的缓冲区个数,另一个记录空缓冲区个数.
g_hSemaphoreBufferEmpty = CreateSemaphore(NULL, 4, 4, NULL);
g_hSemaphoreBufferFull = CreateSemaphore(NULL, 0, 4, NULL);
g_i = 0;
g_j = 0;
memset(g_Buffer, 0, sizeof(g_Buffer));
const int THREADNUM = 3;
HANDLE hThread[THREADNUM];
//生产者线程
hThread[0] = (HANDLE)_beginthreadex(NULL, 0, ProducerThreadFun, NULL, 0, NULL);
//消费者线程
hThread[1] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
hThread[2] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
WaitForMultipleObjects(THREADNUM, hThread, TRUE, INFINITE);
for (int i = 0; i < THREADNUM; i++)
CloseHandle(hThread[i]);
//销毁信号量和关键段
CloseHandle(g_hSemaphoreBufferEmpty);
CloseHandle(g_hSemaphoreBufferFull);
DeleteCriticalSection(&g_cs);
return 0;
}
运行结果如下图所示:
输出结果证明各线程的同步和互斥已经完成了。
至此,生产者消费者问题已经圆满的解决了,下面作个总结:
1.首先要考虑生产者与消费者对缓冲区操作时的互斥。
2.不管生产者与消费者有多少个,缓冲池有多少个缓冲区。都只有二个同步过程——分别是生产者要等待有空缓冲区才能投放产品,消费者要等待有非空缓冲区才能去取产品。
转载请标明出处,原文地址:http://blog.csdn.net/morewindows/article/details/7577591