synchronized class bugs?

Steven Schveighoffer schveiguy at gmail.com
Wed Apr 8 23:25:09 UTC 2020


On 4/8/20 6:50 PM, Gregor Mückl wrote:

> void main()
> {
>      shared Shared s = new shared Shared();
> 
>      s.increment(1);
>      s.decrement(1);
>      writeln(s.get());
> 
>      Thread[] threads = new Thread[10];
>      for(int i = 0; i < threads.length; i++) {
>          threads[i] = new Thread({
>              for(int j = 0; j < 1_000_000; j++) {
>                  s.increment(i);
>              }
>              for(int j = 0; j < 1_000_000; j++) {
>                  s.decrement(i);
>              }
>          });
>          threads[i].start();
>      }
> 
>      for(int i = 0; i < threads.length; i++) {
>          threads[i].join();
>      }
> 
>      writeln(s.get());
> }
> 

The issue is not synchronization of the class data, but your promiscuous 
usage of the stack frame ;)

Try this instead for your loop:

     for(int i = 0; i < threads.length; i++) {
         threads[i] = (int val) { return new Thread({
             for(int j = 0; j < 1_000_000; j++) {
                 s.increment(val);
             }
             for(int j = 0; j < 1_000_000; j++) {
                 s.decrement(val);
             }
         });}(i);


Why doesn't yours work? Because you are starting your threads and then 
changing the value of i as you iterate the loop.

This works, because it captures the i value as a new variable in a 
closure, so `val` remains constant while `i` increments.

-Steve


More information about the Digitalmars-d mailing list