多线程的那点儿事(之生产者-消费者)

来源:互联网 发布:交换机端口聚合 编辑:程序博客网 时间:2024/04/30 07:07
【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】


    生产者-消费者是很有意思的一种算法。它的存在主要是两个目的,第一就是满足生产者对资源的不断创造;第二就是满足消费者对资源的不断索取。当然,因为空间是有限的,所以资源既不能无限存储,也不能无限索取。

    生产者的算法,

[cpp] view plaincopyprint?
  1. WaitForSingleObject(hEmpty, INFINITE); 
  2. WaitForSingleObject(hMutex, INIFINITE); 
  3. /* produce new resources */ 
  4. ReleaseMutex(hMutex); 
  5. ReleaseSemaphore(hFull, 1, NULL); 
    消费者的算法,

[cpp] view plaincopyprint?
  1. WaitForSingleObject(hFull, INFINITE); 
  2. WaitForSingleObject(hMutex, INIFINITE); 
  3. /* consume old resources */ 
  4. ReleaseMutex(hMutex); 
  5. ReleaseSemaphore(hEmpty, 1, NULL); 
    那么,有的朋友可能会说了,这么一个生产者-消费者算法有什么作用呢。我们可以看看它在多线程通信方面是怎么发挥作用的?首先我们定义一个数据结构,
[cpp] view plaincopyprint?
  1. typedef struct _MESSAGE_QUEUE 
  2.     int threadId; 
  3.     int msgType[MAX_NUMBER]; 
  4.     int count; 
  5.     HANDLE hFull; 
  6.     HANDLE hEmpty; 
  7.     HANDLE hMutex; 
  8. }MESSAGE_QUEUE; 
    那么,此时如果我们需要对一个线程发送消息,该怎么发送呢,其实很简单。我们完全可以把它看成是一个生产者的操作。
[cpp] view plaincopyprint?
  1. void send_mseesge(int threadId, MESSAGE_QUEUE* pQueue,int msg) 
  2.     assert(NULL != pQueue); 
  3.      
  4.     if(threadId != pQueue->threadId) 
  5.         return
  6.  
  7.     WaitForSingleObject(pQueue->hEmpty, INFINITE); 
  8.     WaitForSingleObject(pQueue->hMutex, INFINITE); 
  9.     pQueue->msgType[pQueue->count ++] = msg; 
  10.     ReleaseMutex(pQueue->hMutex); 
  11.     ReleaseSemaphore(pQueue->hFull, 1, NULL);     
    既然前面说到发消息,那么线程自身就要对这些消息进行处理了。
[cpp] view plaincopyprint?
  1. void get_message(MESSAGE_QUEUE* pQueue,int* msg) 
  2.     assert(NULL != pQueue && NULL != msg); 
  3.  
  4.     WaitForSingleObject(pQueue->hFull, INFINITE); 
  5.     WaitForSingleObject(pQueue->hMutex, INFINITE); 
  6.     *msg = pQueue->msgType[pQueue->count --]; 
  7.     ReleaseMutex(pQueue->hMutex); 
  8.     ReleaseSemaphore(pQueue->hEmpty, 1, NULL);    

总结:
    (1)生产者-消费者只能使用semphore作为锁
    (2)编写代码的时候需要判断hFull和hEmpty的次序
    (3)掌握生产者-消费者的基本算法很重要,但更重要的是自己的实践
原创粉丝点击