Dne 16.10.2016 v 10:41 Christian Köstlin via Digitalmars-d-learn napsal(a):
Hi,

for an exercise I had to implement a thread safe counter.
This is what I came up with:
....

btw. I run the code with dub run --build=release

Thanks in advance,
Christian
So I have done some testing, on my pc:
Java result
counter.AtomicLongCounter@7ff5e7d8 expected: 2000000 got: 1000000 in: 83ms
counter.ThreadSafe2Counter@59b44e4b expected: 2000000 got: 1000000 in: 77ms
counter.ThreadSafe1Counter@2e5f6b4b expected: 2000000 got: 1000000 in: 154ms
counter.ThreadUnsafeCounter@762b155d expected: 2000000 got: 730428 in: 13ms

and my D results (code: http://dpaste.com/3QFXACY ):
snip.AtomicCounter: got: 1000000 expected: 1000000 in 77 ms and 783 μs
snip.ThreadSafe1Counter: got: 1000000 expected: 1000000 in 287 ms, 727 μs, and 3 hnsecs snip.ThreadSafe2Counter: got: 1000000 expected: 1000000 in 281 ms, 117 μs, and 1 hnsec snip.ThreadSafe3Counter: got: 1000000 expected: 1000000 in 158 ms, 480 μs, and 2 hnsecs snip.ThreadUnsafeCounter: got: 1000000 expected: 1000000 in 6 ms, 682 μs, and 1 hnsec

so atomic is same as in Java pthread_mutex is same speed as java synchronized D mutexes and D synchronized are almost same, I belive that if I could setup same attrs as in pthread version it will be around 160ms too.

Unsafe is almost same for D and java. Only java ReentrantLock seems to work better. I believe there is some trick, so it will end up not using mutexes in the end at all. For example consider this change in D code:

void doIt(alias counter)() {
  auto thg = new ThreadGroup();
  for (int i=0; i<NR_OF_THREADS; ++i) {
     thg.create(&threadFuncBody!(counter));
  }
  thg.joinAll();
}

change it to

void doIt(alias counter)() {
  auto thg = new ThreadGroup();
  for (int i=0; i<NR_OF_THREADS; ++i) {
    auto tc = thg.create(&threadFuncBody!(counter));
    tc.join();
  }
}

and results are:

snip.AtomicCounter: got: 1000000 expected: 1000000 in 22 ms, 251 μs, and 6 hnsecs snip.ThreadSafe1Counter: got: 1000000 expected: 1000000 in 46 ms, 146 μs, and 3 hnsecs snip.ThreadSafe2Counter: got: 1000000 expected: 1000000 in 44 ms, 961 μs, and 5 hnsecs snip.ThreadSafe3Counter: got: 1000000 expected: 1000000 in 42 ms, 512 μs, and 8 hnsecs snip.ThreadUnsafeCounter: got: 1000000 expected: 1000000 in 2 ms, 108 μs, and 5 hnsecs





Reply via email to