C # implement inter-process synchronization

Source: Internet
Author: User

From msdn ..

// This example shows how a mutex is used to synchronize access
// To a protected resource. Unlike monitor, mutex can be used
// Waithandle. waitall and waitany, and can be passed into SS
// Appdomain boundaries.
 
Using System;
Using System. Threading;

Class Test
{
// Create a new mutex. The creating thread does not own
// Mutex.
Private   Static Mutex mut =   New Mutex ();
Private   Const   Int Numiterations =   1 ;
Private   Const   Int Numthreads =   3 ;

Static   Void Main ()
{
// Create the threads that will use the protected resource.
For ( Int I =   0 ; I < Numthreads; I ++ )
{
Thread mythread
=   New Thread ( New Threadstart (mythreadproc ));
Mythread. Name
= String. Format ( " Thread {0} " , I +   1 );
Mythread. Start ();
}

//The main thread exits, but the application continues
//Run until all foreground threads have exited.
}

Private   Static   Void Mythreadproc ()
{
For ( Int I =   0 ; I < Numiterations; I ++ )
{
Useresource ();
}
}

// This method represents a resource that must be synchronized
// So that only one thread at a time can enter.
Private   Static   Void Useresource ()
{
// Wait until it is safe to enter.
Mut. waitone ();

Console. writeline ("{0} has entered the protected area",
Thread. currentthread. Name );

//Place code to access non-reentrant resources here.

// simulate some work.
thread. sleep ( 500 );

console. writeline ( " {0} is leaving the protected area \ r \ n " ,< br> thread. currentthread. name);
// release the mutex.
mut. releasemutex ();
}< BR >}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.