Several semaphore mechanism algorithms

Keywords: Java Algorithm Multithreading Operating System

Producer-consumer questions:

_is too classic to be repeated.

import java.util.concurrent.Semaphore;

public class ProducerAndConsumer {

	static int count = 0;

	private static final Semaphore full = new Semaphore(0);
	private static final Semaphore empty = new Semaphore(20);
	private static final Semaphore mutex = new Semaphore(1);

	public static void main(String[] args) {

		new Thread(()->{
			while (true) {
				try {
					Thread.sleep(100);
					empty.acquire();
					mutex.acquire();
					System.out.println("Producers produce a critical zone resource, and there are" + ++count + "Critical zone resources.");
					mutex.release();
					full.release();
				} catch (InterruptedException e) {
					System.err.println("Something happened that made the thread insecure");
				}
			}
		}).start();

		new Thread(()->{
			while (true) {
				try {
					Thread.sleep(100);
					full.acquire();
					mutex.acquire();
					System.out.println("Consumers consume a critical zone of resources, and there are" + --count + "Critical zone resources.");
					mutex.release();
					empty.release();
				} catch (InterruptedException e) {
					System.err.println("Something happened that made the thread insecure");
				}
			}
		}).start();

	}

}

Multi-producer consumer issues:

A family of four, father, mother, daughter and son are eating. There is a plate on the table. Only one fruit can be put on the table by the parents at a time. Dad puts apples on the table. Mom puts oranges on the table. Son waits for oranges. Daughter waits for apples.

import java.util.concurrent.Semaphore;

/**
 * <b>Synchronization relationship: </b>
 * <li>Daughter can't eat apples until Father releases them</li>
 * <li>The mother released the oranges before the son could eat them </li>
 * <li>Parents can only put fruit </li>when the plate is empty
 * <b>Mutual exclusion: </b>
 * <li>Only one person can pick up or put something on the plate at the same time </li>
 */
public class MultiProducerAndConsume {

	private static final Semaphore orange = new Semaphore(0);
	private static final Semaphore apple = new Semaphore(0);
	private static final Semaphore plate = new Semaphore(1);

	public static void main(String[] args) {

		new Thread(()->{
			while (true) {
				try {
					Thread.sleep(100);
					plate.acquire();
					System.out.println(Thread.currentThread().getName() + "Put the apples on a plate for your daughter to eat.");
					apple.release();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "father").start();

		new Thread(()->{
			while (true) {
				try {
					Thread.sleep(100);
					plate.acquire();
					System.out.println(Thread.currentThread().getName() + "Put the oranges on a plate for your son to eat.");
					orange.release();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "mother").start();

		new Thread(()->{
			while (true) {
				try {
					Thread.sleep(100);
					apple.acquire();
					System.out.println(Thread.currentThread().getName() + "I ate the apple my father gave me.");
					plate.release();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "daughter").start();

		new Thread(()->{
			while (true) {
				try {
					Thread.sleep(100);
					orange.acquire();
					System.out.println(Thread.currentThread().getName() + "I ate an orange from my mother.");
					plate.release();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "Son").start();

	}

}

_Because the buffer size is 1, mutex semaphores are not needed to guarantee mutex exclusion, and mutex settings are not needed like the one above, but if you can put two fruits on a plate at a time, you must have a mutex. Otherwise, after the father has finished the operation on the plate p, the plate is empty, and the mother also operates on the plate p, the plate is empty. Then the parents put the fruit at the same time, and they haveIt is possible to place the same location of the plate, that is, to create data coverage.

Smoking problems:


_There are three smokers who have no cigarettes on their hands: tobacco, paper and glue. They have to get two more materials if they want to smoke. There is also a supplier who will supply two materials which the three smokers lack in turn for free on a table (critical buffer) for the smokers to make their own cigarettes and smoke.

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * <b>Synchronization relationship: </b>
 * <li>There is a set on the table (paper + glue) &rarr's first smoker smokes </li>
 * <li>Combination two (tobacco + glue) on the table & rarr's second smoker smokes </li>
 * <li>There is a set of three (tobacco + paper) &rarr's third smoker smokes </li>
 * <li>Smokers signal completion &rarr supplier places next combination on table </li>
 * <b>Mutual exclusion: </b>
 * <li>Three smokers and suppliers cannot touch the table at the same time (the table is a critical resource)</li>
 */
public class Smoker {

	static final Semaphore[] offer
			= new Semaphore[]{new Semaphore(0), new Semaphore(0), new Semaphore(0)};
	static final Semaphore finish = new Semaphore(0);

	static final Map<Integer, String> map = new HashMap<>();

	static {
		map.put(0, "Paper and glue");
		map.put(1, "Tobacco and glue");
		map.put(2, "Tobacco and paper");
	}

	public static void main(String[] args) {

		new Thread(()->{
			int i  = 0;
			while (true) {
				try {
					offer[i].release();
					System.out.println(Thread.currentThread().getName() + "hold" + map.get(i) + "On the table");
					i = (i +1) % 3;
					finish.acquire();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "supplier").start();

		for (int i = 0; i < 3; i++) {
			int j = i;
			new Thread(()->{
				while (true) {
					try {
						offer[j].acquire();
						System.out.println(Thread.currentThread().getName() + "Take it off the table" + map.get(j) + "And start smoking");
						finish.release();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}, "Smoker" + j + "Number").start();
		}

	}

}

Reader-Writer Questions:


_There are two concurrent processes, Reader and Writer, which share a file. Accessing files simultaneously by more than two reading processes will not have side effects, but when a writing process is running, other processes will not run.

_Therefore, there are the following requirements: (1) Allow multiple readers to read the file at the same time; (2) Allow only one writer to write information to the file; (3) Access critical areas that other processes do not access while the writer is working.

Philosopher's Dining Question:

Posted by dannon on Mon, 20 Sep 2021 20:50:47 -0700