3 summary::control parallel execution of threads
8 Create a new instance, set the maximum number of running threads (default: 1).
13 Determines the number of running threads.
16 Remove any reference to threads, but do not reschedule any pending ones.
19 Stop current thread if already too many are running, otherwise continue.
22 Unblock the semaphore, reschedule next pending thread.
27 // allow only one thread
32 "thread 1> now I am doing something for 10 seconds. Block the semaphore meanwhile.".postln;
35 "thread 1> ok, done. Release the semaphore.".postln;
39 "thread 2> I would like to go on, if I may.".postln;
41 "thread 2> this took until the other thread has released the semaphore. "
42 "Blocking for 4 seconds.".postln;
44 "thread 2> ok, done. Releasing the semaphore".postln;
49 "thread 3> I, too, would like to go on, if I may.".postln;
51 "thread 3> this took until both other threads had released the semaphore.".postln;
58 // allow two threads at a time.
63 "thread 1> now I am doing something for 20 seconds. Block the semaphore.".postln;
65 "thread 1> ok, done. Releasing the semaphore".postln;
70 "thread 2> I would like to go on, if I may.".postln;
71 if(c.count <= 0) { "thread 3> ok, then I wait ...".postln };
73 "thread 1> ok, going ahead.".postln;
75 "thread 2> ok, done. Releasing the semaphore".postln;
80 "thread 3> I, too, would like to go on, if I may.".postln;
81 if(c.count <= 0) { "thread 3> ok, then I wait ...".postln };
83 "thread 3> ok, this took until the first thread had released the semaphore. "
84 "Ok, doing something for 4 seconds. Block the semaphore".postln;
86 "Releasing the semaphore.".postln;
91 "thread 4> Me, the fourth one, would like to go on, if I may.".postln;
92 if(c.count <= 0) { "thread 4> ok, then I wait ...".postln };
94 "thread 4> ok, this took until the third thread had released the semaphore. "
95 "Ok, doing something for 3 seconds. Block the semaphore".postln;
97 "Releasing the semaphore.".postln;
104 // grant exclusive access to data to only one thread
105 // there should never be mixed values in the data array
107 var data, useAndModify;
111 // c = Semaphore(2); use this to test how it would behave without exclusive access.
112 useAndModify = { |newData, who|
113 postln(who + "trying to get blocking access.");
114 if(c.count <= 0) { who + "ok, then I wait ...".postln };
115 c.wait; // may I access? if not, I wait. if yes, disallow others.
117 (who + "continuing...").postln;
123 newData.do { |x, i| data[i] = x };
124 postln(who + "rewriting data to:" + newData);
125 postln(who + "releasing");
126 c.signal; // allow others access again
129 // e.g. set the values to integers
132 useAndModify.value([100, 200, 300], "thread 1>");
137 // e.g. set the values to floats
141 useAndModify.value([pi, 0.5pi, 2pi], "thread 2>");