Synchronous threads using TSemaphore (v5.30 VC++9.0 Win7)

I’m having trouble getting this code to work properly. The code creates two semaphores set to 0, then creates N threads each waiting on the first semaphore. For each iteration, the code posts N times to the first semaphore and waits N times for the second. In each thread, it first waits for the first semaphore, then does the calculation, and finally posts to the second semaphore before repeating. At least, that’s what it’s supposed to do. Unfortunately, it never seems to run on more than 1 thread (see below). The ThreadTest constructor takes the number of threads N and run uses a stopwatch to time the test and display that result. The CPU usage chart displays the three attempts below.


  •                                     *
  •    W E L C O M E  to  R O O T       *
  •                                     *
  • Version 5.30/00 27 June 2011 *
  •                                     *
  • You are welcome to visit our Web site *
  •            *
  •                                     *

ROOT 5.30/00 (tags/v5-30-00@40062, Jun 28 2011, 11:49:57 on win32)

CINT/ROOT C/C++ Interpreter version 5.18.00, July 2, 2010
Type ? for help. Commands must be C++ statements.
Enclose multiple statements between { }.
root [0] .L tools/ThreadTest.cpp+
root [1] ThreadTest test1(1),test2(4),test3(8);
root [2] test1->run()
root [3] test2->run()
root [4] test3->run()
root [5][/code]
Am I using these wrong? Is there a better way to do this? Is this a bug?
ThreadTest.cpp (1.62 KB)
ThreadTest.h (1014 Bytes)


This cannot work. A semaphore has only two states, signalled or not. So this kind of code:

for (Int_t i=0;i<N;i++) { s1.Post(); } for (Int_t i=0;i<N;i++) { s2.Wait(); } is useless, and removing the “for()” statements will behave the same. Only one thread will run… So you should find another way.
BTW, I don’t really know what you’re trying to achieve, but why not simply starting the thread(s) in your ThreadTest::run() and using a join() method? (see for example the macros in $ROOTSYS/tutorials/thread and the $ROOTSYS/test/threads.cxx application)

Cheers, Bertrand.

Thanks Bertrand,
I had tried something like that before making ThreadTest, but I saw no improvement in speed when using in my analysis. I thought that it was caused by overhead from starting/joining the threads 10^5 times so this was my attempt to work around that. Apparently that’s not the case since ThreadTest with run/join shows a significant improvement. There must be something else in my code preventing it from scaling.