Last active
February 5, 2022 08:31
-
-
Save DeivAstra/61fb8a64fe6991d50c3c5115aedfe6c4 to your computer and use it in GitHub Desktop.
Using Semaphore in multithreaded class (D language)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module multithread.semaphore.test; | |
| import std.stdio; | |
| import core.sync.semaphore; | |
| import core.thread.osthread; | |
| import core.time; | |
| import std.random; | |
| import std.conv; | |
| void main() { | |
| testMultithread(); | |
| } | |
| void testMultithread() { | |
| A a = new A(); | |
| // put values | |
| new Thread({ | |
| while(true) { | |
| auto rnd = uniform(0, 100); | |
| a.put(to!string(rnd)); | |
| sleep(4); | |
| } | |
| }).start(); | |
| // print values | |
| new Thread({ | |
| while(true) { | |
| writeln(a.get()); | |
| sleep(3); | |
| } | |
| }).start(); | |
| } | |
| void sleep(int sec) { | |
| Thread.sleep( dur!("seconds")(sec) ); | |
| } | |
| class A { | |
| private shared string [] arr = new string[0]; | |
| private Semaphore sem; | |
| this() { | |
| this.sem = new Semaphore(); | |
| // remove values | |
| new Thread({ | |
| sem.wait(); // waiting first put to start removing | |
| writeln("remover run!"); | |
| while(true) { | |
| try { | |
| synchronized(sem) { | |
| string [] values = get(); | |
| if(values.length > 1) { | |
| auto rnd = uniform(0, values.length - 1); | |
| remove(values[rnd]); | |
| } else writeln("Too few values to remove"); | |
| } | |
| sleep(5); | |
| } catch(Exception e) { | |
| writeln(e); | |
| return; | |
| } | |
| } | |
| }).start(); | |
| } | |
| string[] get() { | |
| synchronized(sem) { | |
| try { | |
| write("sync get"); | |
| return cast(string[]) arr.dup; | |
| } finally { | |
| writeln("."); | |
| } | |
| } | |
| } | |
| private void put(string v) { | |
| synchronized(sem) { | |
| write("sync put"); | |
| arr ~= v; | |
| writef("/%s", v); | |
| this.sem.notify(); // notify to start removing | |
| writeln("."); | |
| } | |
| } | |
| private void remove(string v) { | |
| synchronized(sem) { | |
| writef("sync remove/%s", v); | |
| shared string [] result; | |
| for(int i = 0; i < arr.length; i++) { | |
| if(arr[i] != v) result ~= arr[i]; | |
| } | |
| this.arr = result; | |
| writeln("."); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment