
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Using Events to Make Threads Cooperate
|
1057
See Also
See the “Mutex” and “Mutex Class” topics in the MSDN documentation and Pro-
gramming Applications for Microsoft Windows, Fourth Edition.
18.12 Using Events to Make Threads Cooperate
Problem
You have multiple threads that need to be served by a server but only one can be
served at a time.
Solution
Use an AutoResetEvent to notify each thread when it is going to be served. For exam-
ple, a diner has a cook and multiple waitresses. The waitresses can keep bringing in
orders, but the cook can serve up only one at a time. You can simulate this with the
Cook class shown in Example 18-13.
uint dwMaximumSizeHigh,
uint dwMaximumSizeLow, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint
dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow,
IntPtr dwNumberOfBytesToMap);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
#endregion
}
Example 18-13. Using events to make threads cooperate
public class Cook
{
public static AutoResetEvent OrderReady = new AutoResetEvent(false);
public void ...