How to use core.thread.Thread

Daniel Kozák via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 16 02:17:28 PDT 2015


On Thu, 16 Jul 2015 07:57:10 +0000
aki via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> 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.
> 

import core.thread;
class DerivedThread : Thread {
    shared int count = 0;
    __gshared int count2 = 0;
    this() {
        super(&run);
    }
    private void run() {
        inc();
        inc2();
    }
    void inc() {
        import core.atomic; 
        atomicOp!"+="(this.count, 1);
    }
    
    void inc2() {
        synchronized {
            ++count2;
        }
    }
}
void main() {
    auto thr = new DerivedThread();
    thr.start();
    thr.inc();
    thr.inc2();
    thr.join();
}


More information about the Digitalmars-d-learn mailing list