Producer-consumer is an interesting algorithm. Its existence mainly serves two purposes. The first is to satisfy the producer's constant creation of resources, and the second is to satisfy the consumer's constant demand for resources. Of course, because space is limited, resources cannot be stored infinitely or requested infinitely.
Producer Algorithm
WaitForSingleObject(hEmpty, INFINITE); WaitForSingleObject(hMutex, INIFINITE); /* produce new resources */ ReleaseMutex(hMutex); ReleaseSemaphore(hFull, 1, NULL);
Consumer Algorithms
WaitForSingleObject(hFull, INFINITE); WaitForSingleObject(hMutex, INIFINITE); /* consume old resources */ ReleaseMutex(hMutex); ReleaseSemaphore(hEmpty, 1, NULL);
Some may say, what is the role of such a producer-consumer algorithm. Let's see how it works in multi-thread 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, if we need to send a message to a thread at this time, how can we send it? It is actually very simple. We can regard it as a producer operation.
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 have talked about sending messages, the thread itself needs 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) The producer-consumer can only use semphore as the lock
(2) determine the sequence of hfull and hempty when writing code.
(3) It is important to master the basic algorithm of producer-consumer, but more importantly, it is your own practice.