NextArticle, Let's talk about hostingCodeHow to package Windows kernel objects for Thread Synchronization
The kernel objects for synchronization provided by Windows include mutex, semaphores, and events. System. the waithandle class (abstract base class) in the threading namespace is used to package these kernel objects. classes that package kernel objects for synchronization in managed mode are naturally inherited from the waithandle class, including mutex, semaphore, and eventwaithandle (base class ). The four classes mentioned above override the waitone () method and implement the static waitall (), waitany () and signalandwait () methods, the four methods allow waiting for an object to receive a signal or all objects in the array to receive a signal, waiting for at least one object in the array to receive a signal and sending a signal to one object and waiting for another object. These classes must be instantiated before they can be used. Therefore, the object to be considered here is not a synchronized object but a synchronized object, which means that the object is passed as a parameter to waitall (), waitany () and the objects of the signalandwait () static method are all mutex, events, or semaphores.
First, let's take a look at the use of mutex.
Method 5: Use the mutex class
You can use the same mutex in multiple processes on the same machine or even multiple machines (with. Net remoting required. Cross-process synchronization is the biggest characteristic of mutex compared with the monitor class. Therefore, if the access to be synchronized is in a process, use monitor instead of mutex, the former is much more efficient.
The following example constructs a famous mutex to protect access to resources. The mutex is shared by multiple processes on the same machine.
Static Void Main (){
// Create a mutex named 'mutextest'
Mutex mutexfile = New Mutex ( False , " Mutextest " );
For ( Int I = 0 ; I < 10 ; I ++ ){
Mutexfile. waitone ();
// Open the file, write 'Hello I ', and close the file.
Fileinfo fi = New Fileinfo ( " Tmp.txt " );
Streamwriter SW = Fi. appendtext ();
Sw. writeline ( " Hello {0} " , I );
Sw. Flush ();
Sw. Close ();
System. Console. writeline ( " Hello {0} " , I );
// Wait 1 second to show the effect of the mutex
Thread. Sleep ( 1000 );
Mutexfile. releasemutex ();
}
Mutexfile. Close ();
}
Waitone ()The method blocks the current thread and knows to obtain the mutex. UseReleasemutex ()Method to release the mutex.
Note,ProgramMediumNew mutex ()Not necessarily a mutex is created. It may be a pair of mutex."Mutextest". The system creates a mutex only when it does not exist. (Only when no other process is referenced,Close ()).
Method6: Event
an event is used to send notifications between threads. This notification indicates that an event has occurred. Events of interest and autoresetevent and manualresetevent An instance is associated with the two event classes. (Use eventresetmode medium autoreset or manualreset one of the two enumeration types can avoid creating a new instance.)
Specifically, a thread callsWaitone ()This blocking method is used to wait for an event to be triggered. The other thread callsSet ()Method To trigger the event so that a thread can continue to execute.
Static Eventwaithandle [] events;
Static Void Main (){
Events = New Eventwaithandle [ 2 ];
// Initialization event status: false
Events [ 0 ] = New Eventwaithandle ( False , Eventresetmode. autoreset );
Events [ 1 ] = New Eventwaithandle ( False , Eventresetmode. autoreset );
Thread t0 = New Thread (threadproc0 );
Thread T1 = New Thread (threadproc1 );
T0.start (); t1.start ();
Autoresetevent. waitall (events );
Console. writeline ( " Mainthread: thread0 reached 2 " +
" And thread1 reached 3. " );
T0.join (); t1.join ();
}
Static Void Threadproc0 (){
For ( Int I = 0 ; I < 5 ; I ++ ){
Console. writeline ( " Thread0: {0} " , I );
If (I = 2 ) Events [ 0 ]. Set ();
Thread. Sleep ( 100 );
}
}
Static Void Threadproc1 (){
For ( Int I = 0 ; I < 5 ; I ++ ){
Console. writeline ( " Thread1: {0} " , I );
If (I = 3 ) Events [ 1 ]. Set ();
Thread. Sleep ( 60 );
}
}
Difference between manual resetting and automatic resetting: If several threads are waiting for the same automatic reset event, this event needs to be triggered once for each thread, in the case of manual resetting, you only need to trigger an event for all the blocked threads to continue execution.
Method7: Semaphore
Semaphores-SemaphoreClass instances are used to limit the number of concurrent workers for a resource. WhenWaitone ()When the method tries to enter a semaphore, if the number of threads that have already entered reached a certain maximum value, the thread will be blocked. The maximum number of entries isSemaphoreClass constructor second parameter settings, and the first parameter defines the number of entries in the initial period. If the value of the first parameter is smaller than the second parameter, the thread automatically occupies the entry of the number of interpolation between the two parameters when calling the constructor. This also shows that the same thread can occupy multiple portals of the same semaphore.
Example:
Static Semaphore semaphore;
Static Void Main (){
// Number of empty slots initialized: 2.
// Maximum number of slots that can be used simultaneously: 5.
// Number of slots owned by the main thread: 3 (5-2 ).
Semaphore = New Semaphore ( 2 , 5 );
For ( Int I = 0 ; I < 3 ; ++ I ){
Thread t = New Thread (workerproc );
T. Name = " Thread " + I;
T. Start ();
Thread. Sleep ( 30 );
}
}
Static Void Workerproc (){
For ( Int J = 0 ; J < 3 ; J ++ ){
Semaphore. waitone ();
Console. writeline (thread. currentthread. Name + " : Begin " );
// Simulate a. 2 s task
Thread. Sleep ( 200 );
Console. writeline (thread. currentthread. Name + " : End " );
Semaphore. Release ();
}
}
In the above program, the main thread occupies3Portal, forcing another3Threads to share the remaining2Entries. From the running result, you can see that the number of concurrent jobs has never exceeded2.
The thread synchronization method I have learned is described in the two articles.7Type. Please add it!