[notice: All Rights Reserved. Please reprint. Do not use for commercial purposes. Contact email: feixiaoxing@163.com]
Producer consumer is an interesting algorithm. Its existence is mainly for two purposes, the first is to meet the continuous creation of resources by producers; the second is to meet the continuous demand of resources by consumers. Of course, because of the limited space, resources can neither be stored nor acquired indefinitely.
Producer's algorithm,
-
WaitForSingleObject(hEmpty, INFINITE);
-
WaitForSingleObject(hMutex, INIFINITE);
-
-
ReleaseMutex(hMutex);
-
ReleaseSemaphore(hFull, 1, NULL);
Consumer's algorithm,
-
WaitForSingleObject(hFull, INFINITE);
-
WaitForSingleObject(hMutex, INIFINITE);
-
-
ReleaseMutex(hMutex);
-
ReleaseSemaphore(hEmpty, 1, NULL);
Then, some friends may say, what is the function of such a producer consumer algorithm. Let's see how it works in multithreaded communication? First, we define a data structure,
-
typedef struct _MESSAGE_QUEUE
-
{
-
int threadId;
-
int msgType[MAX_NUMBER];
-
int count;
-
HANDLE hFull;
-
HANDLE hEmpty;
-
HANDLE hMutex;
-
}MESSAGE_QUEUE;
So, at this time, if we need to send messages to a thread, how to send them is very simple. We can think of it as the operation of a producer.
-
void send_mseesge(int threadId, MESSAGE_QUEUE* pQueue, int msg)
-
{
-
assert(NULL != pQueue);
-
-
if(threadId != pQueue->threadId)
-
return;
-
-
WaitForSingleObject(pQueue->hEmpty, INFINITE);
-
WaitForSingleObject(pQueue->hMutex, INFINITE);
-
pQueue->msgType[pQueue->count ++] = msg;
-
ReleaseMutex(pQueue->hMutex);
-
ReleaseSemaphore(pQueue->hFull, 1, NULL);
-
}
Now that we talked about sending messages, the thread itself has to process these messages.
-
void get_message(MESSAGE_QUEUE* pQueue, int* msg)
-
{
-
assert(NULL != pQueue && NULL != msg);
-
-
WaitForSingleObject(pQueue->hFull, INFINITE);
-
WaitForSingleObject(pQueue->hMutex, INFINITE);
-
*msg = pQueue->msgType[pQueue->count --];
-
ReleaseMutex(pQueue->hMutex);
-
ReleaseSemaphore(pQueue->hEmpty, 1, NULL);
-
}
Summary:
(1) producer consumer can only use sempoint as lock
(2) when writing code, you need to judge the order of hFull and hEmpty
(3) it's very important to master the basic algorithm of producer consumer, but more importantly, it's own practice