A few days ago, a student asked me to help him develop the producer-consumer simulation program in the operating system course. The requirement is as follows: encapsulate the producer and consumer simulation algorithms in a dynamic link library, the main program calls related functions. The speed at which the producer places the product and the consumer to remove the product can be adjusted. Use the cyclic queue and stack respectively. This algorithm is used to simulate production. The consumer opens a thread to access a shared buffer synchronously. However, the requirement can adjust the speed. My idea is to create a timer in each thread, but in windows, the Timer feature is: Every scheduled time, in Windows, A wm_timer message is put into the message queue of the application. So my solution is as follows:
- /* Change the timer message */
- # Define wm_settimer wm_user+ 100
- /* Producer thread function */
- DWORD winapi producerfunc (lpvoid lpparameter)
- {
- MSG;
- Uint producertimerid;
- /* Create a message queue for this thread */
- Peekmessage (& MSG, null, 0, 0, pm_noremove );
- Producertimerid = settimer (null, 0, g_uproducertimer, null );
- While (getmessage (& MSG, null, 0, 0 ))
- {
- If (msg. Message = wm_timer)
- {
- Waitforsingleobject (g_hemptysemaphore, infinite );
- Waitforsingleobject (g_hmutex, infinite );
- Producer ();
- Releasemutex (g_hmutex );
- Releasesemaphore (g_hfullsemaphore, 1, null );
- }
- Else if (msg. Message = wm_settimer)
- {
- Killtimer (null, producertimerid );
- Producertimerid = settimer (null, 0, g_uproducertimer, null );
- }
- Else
- {
- Translatemessage (& MSG );
- Dispatchmessage (& MSG );
- }
- }
- Killtimer (null, producertimerid );
- Return 0;
- }
- /* Consumer thread function */
- DWORD winapi consumerfunc (lpvoid lpparameter)
- {
- MSG;
- Uint consumertimerid;
- Peekmessage (& MSG, null, 0, 0, pm_noremove );
- Consumertimerid = settimer (null, 0, g_uconsumertimer, null );
- While (getmessage (& MSG, null, 0, 0 ))
- {
- If (msg. Message = wm_timer)
- {
- Waitforsingleobject (g_hfullsemaphore, infinite );
- Waitforsingleobject (g_hmutex, infinite );
- Consumer ();
- Releasemutex (g_hmutex );
- Releasesemaphore (g_hemptysemaphore, 1, null );
- }
- Else if (msg. Message = wm_settimer)
- {
- Killtimer (null, consumertimerid );
- Consumertimerid = settimer (null, 0, g_uconsumertimer, null );
- }
- Else
- {
- Translatemessage (& MSG );
- Dispatchmessage (& MSG );
- }
- }
- Killtimer (null, consumertimerid );
- Return 0;
- }
We hope you can provide a better solution.
Complete source code here: http://download.csdn.net/source/880262