Variable modified by different threads.

Salih Dincer salihdb at hotmail.com
Mon Dec 2 06:16:29 UTC 2024


On Monday, 2 December 2024 at 02:02:56 UTC, Ritina wrote:
> How can I implement a program where I have a global integer 
> variable g, and three threads: the first thread increments g by 
> 1, the second thread increments g by 2, and the third thread 
> increments g by 3? Additionally, while these threads are 
> running, I should be able to access the value of g both inside 
> and outside the threads.

When we ask claude.ai what is to be done, we get a very clear and 
great answer. This shows that D is an easy language. Yes, if the 
result is 600, each thread has increased it 100 times 
individually:

```d
import std.conv, std.stdio;
import core.sync.mutex;
import core.atomic;
import core.thread;

struct GlobalCounter
{
     // Mutex to protect shared access to the global variable
     private Mutex mutex;
     // The global integer variable to be incremented
     private shared int gInt;

     // Method to safely increment the global variable
     void increment(int value)
     {
         synchronized(mutex)
         {
             gInt.atomicOp!"+="(value);
         }
     }

     // Getter method to safely read the global variable
     string toString()
     {
         synchronized(mutex)
         {
             return gInt.to!string;
         }
     }
}

void main()
{
     // Create a shared counter instance
     GlobalCounter counter;

     // Initialize the mutex
     counter.mutex = new Mutex();

     // Create three threads with different increment values
     auto thread1 = new Thread(()
     {
         for (int i = 0; i < 100; i++)
         {
             counter.increment(1);
         }
     });

     auto thread2 = new Thread(()
     {
         for (int i = 0; i < 100; i++)
         {
             counter.increment(2);
         }
     });

     auto thread3 = new Thread(()
     {
         for (int i = 0; i < 100; i++)
         {
             counter.increment(3);
         }
     });

     // Start all threads
     thread1.start();
     thread2.start();
     thread3.start();

     // Wait for all threads to complete
     thread1.join();
     thread2.join();
     thread3.join();

     // Print the final value
     counter.writefln!"Final value: %s";
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list