Предположим, есть несколько читателей и писателей, которые хотят выполнить операцию чтения или записи для одного и того же содержимого.Читатели могут читать содержимое одновременно, в то время как только один писатель может писать одновременно.
Кроме того, писатель должен иметь более высокий приоритет, чем читатель.
Ниже моя мысль реализована с использованием Java, ноэто вызывает мертвый замок.В чем проблема или кто-нибудь знает, как сделать писателя более высоким приоритетом?
package com.multithread.readandwrite;
import java.util.concurrent.Semaphore;
public class WriteFirst {
private static class Reader extends Thread {
Semaphore write_waiting, read_count_mutex, use;
volatile int readcount;
public Reader(Semaphore write_waiting, Semaphore read_count_mutex, Semaphore use, int readcount) {
this.write_waiting = write_waiting;
this.read_count_mutex = read_count_mutex;
this.use = use;
this.readcount = readcount;
}
@Override
public void run() {
super.run();
try {
write_waiting.acquire();
write_waiting.release();
read_count_mutex.acquire();
System.out.println(readcount);
if (readcount++ == 0)
use.acquire();
read_count_mutex.release();
// mock read
sleep(1);
System.out.println(getName());
read_count_mutex.acquire();
if (--readcount == 0)
use.release();
read_count_mutex.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class Writer extends Thread {
Semaphore write_count_mutex, use, write_waiting;
volatile int write_count;
public Writer(Semaphore write_count_mutex, Semaphore use, Semaphore write_waiting, int write_count) {
this.write_count_mutex = write_count_mutex;
this.use = use;
this.write_waiting = write_waiting;
this.write_count = write_count;
}
@Override
public void run() {
super.run();
try {
write_count_mutex.acquire();
System.out.println(write_count);
if (write_count++ == 0)
write_waiting.acquire();
write_count_mutex.release();
use.acquire();
//mock write
sleep(1);
System.out.println(getName());
use.release();
write_count_mutex.acquire();
if (--write_count == 0)
write_waiting.release();
write_count_mutex.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Semaphore use = new Semaphore(1), write_count_mutex = new Semaphore(1), read_count_mutex = new Semaphore(1),
write_waiting = new Semaphore(1);
int read_count = 0, write_count = 0;
Reader[] readers = new Reader[100];
Writer[] writers = new Writer[100];
for (int i=0; i<100; i++) {
readers[i] = new Reader(write_waiting, read_count_mutex, use, read_count);
readers[i].setName("reader "+i);
writers[i] = new Writer(write_count_mutex, use, write_waiting, write_count);
writers[i].setName("writer "+i);
}
for (int i=0; i<100; i++) {
readers[i].start();
writers[i].start();
}
int i = 0;
}
}