Synchronized const methods
Tomek Sowiński
just at ask.me
Fri Jun 11 15:08:49 PDT 2010
If a synchronized method call sees that someone's already partying with
its object, it waits. So far so good. Now here's something I don't quite
get: if a *const* synchronized method call sees that another const
synchronized method call is holding the lock, then why it needs to be held
up? D features deep const; that's a promise strong enough to drop the
sync'ing, no?
Example:
import std.stdio;
import core.thread;
shared class K {
string value;
this (string value) {
this.value = value;
}
synchronized void metoda() const {
foreach (i; 0..3) {
writeln(Thread.getThis().name, " is calling metoda. My value
is ", value);
Thread.sleep(1_000_000);
}
}
}
class My_Thread : Thread {
K k;
this(K k, string name) {
super(&run);
this.k = k;
this.name = name;
}
void run() {
k.metoda();
}
}
void main() {
K k = new K("some value");
(new My_Thread(k, "Thread 1")).start();
(new My_Thread(k, "Thread 2")).start();
}
Now, sync'ing would be necessary if one of the threads could mutate K, but
here?
The output is:
Thread 1 is calling metoda. My value is some value
Thread 1 is calling metoda. My value is some value
Thread 1 is calling metoda. My value is some value
Thread 2 is calling metoda. My value is some value
Thread 2 is calling metoda. My value is some value
Thread 2 is calling metoda. My value is some value
Tomek
More information about the Digitalmars-d-learn
mailing list