That’s such a complex example for achieving so little. A few observations.
-
You seem to be changing the thread from Preemptive to Cooperative in an attempt to provide critical section synchronisation. You would be far better creating a single CriticalSection or Semaphore, setting its type to Preemptive and using that for synchronising. Who knows how long this will take given you have two copies of the tread working at the same time, it’s quite possible that nothing happens until all of the copies are switched mode.
-
You appear to be creating a class that then instantiates a thread and starts it. While that may be good for the long term it makes this “simple” example rather difficult to follow.
-
The code seems to do very little other than increment a share variable and change states. Which is a really bad use for threads. Topically you want something long that a work in the background. Making multiple copies of it if you can do something in parallel will help.
-
All you have effectively done here is create a pair of threads that are going to fight over access to the single shared variable you are incrementing.