How to use core.thread.Thread

byron via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 16 14:48:05 PDT 2015


On Thursday, 16 July 2015 at 07:57:13 UTC, aki wrote:
> I can't resolve the compile errors:
>
> import core.thread;
> class DerivedThread : Thread {
> 	int count = 0;
> 	this() {
> 		super(&run);
> 	}
> 	private void run() {
> 		inc();	//testThread.d(8): Error: shared method 
> testThread.DerivedThread.inc is not callable using a non-shared 
> object
> 	}
> 	synchronized void inc() {
> 		++count;	//testThread.d(11): Deprecation: read-modify-write 
> operations are not allowed for shared variables. Use 
> core.atomic.atomicOp!"+="(this.count, 1) instead.
> 	}
> }
> void main() {
> 	auto thr = new DerivedThread();
> 	thr.start();
> 	thr.inc();	//testThread.d(17): Error: shared method 
> testThread.DerivedThread.inc is not callable using a non-shared 
> object
> 	thr.join();
> }
>
>
> 1. Should I declare thr as shared? But
> 	auto thr = new shared DerivedThread();
> does not resolve it.
>
> 2. Why "++count" cause an error? I think it is safe because
> it is marked as synchronized. If it is forced to use atomicOp
> all the time, it's painful.
>
> 3. Are there any tutorials about using Thread class?
>
> Aki.



If I remember a synchronized method requires "this" to be shared, 
you should be fine using a synchronized block in the method for 
non-shared instances.  But using atomicOp will avoid a lock.

void inc() {
   synchronized {
		++count;
   }
}

You are locking on this object instance by default


More information about the Digitalmars-d-learn mailing list