[phobos] Parallelism in Phobos

Denis 2korden at gmail.com
Fri Aug 27 09:45:38 PDT 2010


I'm not an asm guru in any way, so there might be hidden bugs in my
code, but still here is my version:

import std.perf;
import std.stdio;

void atomicIncUint(ref shared(uint) num) {
    asm {
//        mov EAX, num; //< no need to move num to EAX since last
argument is always passed in EAX and DMD doesn't inline functions that
use asm or alloca
        lock;
        inc int ptr [EAX];
//      mov EAX, [EAX]; // ???
    }
}

uint atomicIncUintViaCas(ref shared(uint) num) {
    asm {
        mov EDX, num;
repeat:
        mov EAX, [EDX];
        mov ECX, EAX;
        inc ECX;
        lock;
        cmpxchg [EDX], ECX;
        jnz repeat;

}

void main() {
    auto pc = new PerformanceCounter;
    pc.start;

    shared uint num = 111;
    for (uint i = num; i < 100_000_000; ++i) {
        //atomicIncUint(num);	// 2060
        atomicIncUintViaCas(num);	// 2199
    }
	
    pc.stop;
    writeln(pc.milliseconds);
    writeln(cast(uint)num); // wtf? why writeln doesn't allow printing
shared stuff?
}

I think the difference is pretty much negligible, but with
atomicIncUintViaCas you have a benefit of returning old variable value
(which is a nice thing to have).


More information about the phobos mailing list