Synchronization of Java and operating system processes (i) ———— Mutex issues

Source: Internet
Author: User
Tags mutex semaphore

The school has recently opened the operating system principle course, the teacher asked to use any language to simulate the process of synchronization and mutual exclusion problems.

After trying to write, found that the problem is very interesting, so want to record in the blog, as their learning trajectory.

People prefer to use the Java language, so they use Java to write. Today is the issue of multiple processes accessing the amount of mutex resources, mutual exclusion is a resource at the same time, allowing only one process access, in discrete mathematics, the mutex is defined as follows

The intersection of events A and B is empty, and A and B are mutually exclusive events, also known as incompatible events. It can also be described as: an event that cannot occur simultaneously. If A∩B is not an event (a∩b=φ), then event A is mutually exclusive with event B, meaning that event A and event B do not occur simultaneously in any one experiment (Baidu Encyclopedia).

such as the daily life of the printer, is a public resource, the same time, only allow one task to do, other tasks queued waiting.

The record-based signal volume is used to achieve this.

The corresponding wait (Semaphore s) (The wait operation is the P operation, which is the term in our textbook) is the pseudo-code

1 Wait (Semaphore *s) {2      s->value--; Value is the number of resources 3      if0) {4           block (s->list);       List is PCB (process_control_block) block 5     }6 }    

The pseudo-code for the corresponding signal (signal is the V operation) is:

Signal (Semaphore *s) {       s->value++;        if 0 )             Wakeup (S-tolist);}

So first we have to implement a semaphore class, using synchronized block to simulate wait and signal operation, specific synchronized details please Baidu or other blog park articles, I understand is not particularly thorough.

 Public class          Semaphore {    publicnew  Object ();                   Synchronized lock is the object     public   int  value;        Number of resources public Semaphore (int  value)        {this. value =    value;}    }

In this class we implement the wait and Signal methods

     Public Static  voidWait (Semaphore semaphore,string className) {//classname is used to judge the threadsynchronized(semaphore.lock) {Semaphore.value--; if(Semaphore.value < 0)            {                Try{System.out.println (className+ "blocked");                            Semaphore.lock.wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }                        }         Public Static  voidSignal (Semaphore semaphore,string className) {synchronized(semaphore.lock) {Semaphore.value++; if(Semaphore.value <= 0) {System.out.println (ClassName+ "Enough resources to wake up one");            Semaphore.lock.notify (); }        }            }    

You can see that the basic idea of pseudo-code is the same as in the beginning.

By this we have completed the recorded signal volume.

Now we're going to use the record-type semaphore to complete the mutex relationship.

First, the pseudo-code to complete the mutual-exclusion relationship with the recorded semaphore is given.

operation () {     while (1) {        wait (mutex);          // Enter the critical section         signal (mutex);         // remaining Area     }}    

Critical section: The code that accesses critical resources in the process

We simulate multiple people using printers to simulate process mutex issues.

Generally solve the synchronization problem to determine the signal volume, mutual exclusion signal is very good to determine, is the printer, we can set the initial printer resources of 1

The first is to complete a runnable subclass, which is the operation of the printer, that is, for the above operation

 Public classPrinteruserImplementsrunnable{//Printer Signal VolumeSemaphore printer;
Confirm thread identity String userName; PublicPrinteruser (Semaphore printer,string userName) {//TODO Auto-generated constructor stub This. Printer =printer; This. UserName =UserName; } @Override Public voidrun () {//TODO Auto-generated method stubs while(true) {semaphore.wait (printer, userName); System.out.println ("Printing"); Semaphore.signal (printer, userName); System.out.println (UserName+ "Print Complete"); } }}

Give the test

 Public Static void Main (string[] args) {        new Semaphore (1);         // TODO auto-generated Method stub        New Thread (new printeruser (printer, "Print 1"));        Thread threadbnew thread (new printeruser (printer, "Print 2"));                Threada.start (); Threadb.start ();    }

Test results

Synchronization of Java and operating system processes (i) ———— Mutex issues

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.