定时器与多线程 SetTimer and Multi-Thread 每个线程独立使用一个定时器

来源:互联网 发布:mac的手绘软件 编辑:程序博客网 时间:2024/05/17 02:22
前几天,一个同学让我帮他做操作系统课程里的 生产者——消费者 模拟程序,需求如下:
  将生产者和消费者模拟算法封装在一个动态链接库中,主程序调用相关函数。生产者放入产品和消费者取走产品的速度可调节。
分别用循环队列和栈实现。

一般模拟这个算法都是生产这,消费者各开一个线程,同步访问一个共享缓冲区。但是需求要求能调节速度,我的思路是在
每个线程里单独创建一个定时器,但是Windows下定时器特性是:
   每隔定时时间,Windows系统放入一个 WM_TIMER 消息到应用程序的消息队列中。
所以我的解决方案如下:
  1. /* 更改定时器的消息 */
  2. #define WM_SETTIMER WM_USER + 100
  3. /* 生产者线程函数 */
  4. DWORD WINAPI ProducerFunc(LPVOID lpParameter)
  5. {
  6.     MSG msg;
  7.     UINT producerTimerId;
  8.     /* Create a message queue for this thread */
  9.     PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
  10.     producerTimerId = SetTimer(NULL, 0, g_uProducerTimer, NULL);
  11.     while(GetMessage(&msg, NULL, 0, 0))
  12.     {
  13.         if(msg.message == WM_TIMER)
  14.         {
  15.             WaitForSingleObject(g_hEmptySemaphore, INFINITE);
  16.             WaitForSingleObject(g_hMutex, INFINITE);
  17.             Producer();
  18.             ReleaseMutex(g_hMutex);
  19.             ReleaseSemaphore(g_hFullSemaphore, 1, NULL);
  20.         }
  21.         else if(msg.message == WM_SETTIMER)
  22.         {
  23.             KillTimer(NULL, producerTimerId);
  24.             producerTimerId = SetTimer(NULL, 0, g_uProducerTimer, NULL);
  25.         }
  26.         else
  27.         {
  28.             TranslateMessage(&msg);
  29.             DispatchMessage(&msg);
  30.         }
  31.     }
  32.     KillTimer(NULL, producerTimerId);
  33.     return 0;
  34. }
  35. /* 消费者线程函数 */
  36. DWORD WINAPI ConsumerFunc(LPVOID lpParameter)
  37. {
  38.     MSG msg;
  39.     UINT consumerTimerId;
  40.     PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
  41.     consumerTimerId = SetTimer(NULL, 0, g_uConsumerTimer, NULL);
  42.     while(GetMessage(&msg, NULL, 0, 0))
  43.     {
  44.         if(msg.message == WM_TIMER)
  45.         {
  46.             WaitForSingleObject(g_hFullSemaphore, INFINITE);
  47.             WaitForSingleObject(g_hMutex, INFINITE);
  48.             Consumer();
  49.             ReleaseMutex(g_hMutex);
  50.             ReleaseSemaphore(g_hEmptySemaphore, 1, NULL);
  51.         }
  52.         else if(msg.message == WM_SETTIMER)
  53.         {
  54.             KillTimer(NULL, consumerTimerId);
  55.             consumerTimerId = SetTimer(NULL, 0, g_uConsumerTimer, NULL);
  56.         }
  57.         else
  58.         {
  59.             TranslateMessage(&msg);
  60.             DispatchMessage(&msg);
  61.         }
  62.     }
  63.     KillTimer(NULL, consumerTimerId);
  64.     return 0;
  65. }
希望各位大侠提供一个更好的解决方案。
完整的源代码在这里:
http://download.csdn.net/source/880262
原创粉丝点击