Variable modified by different threads.
Salih Dincer
salihdb at hotmail.com
Mon Dec 2 07:56:52 UTC 2024
On Monday, 2 December 2024 at 02:29:39 UTC, Ali Çehreli wrote:
> ...
> There are several other methods of communicating the request..
I've slightly edited the code that the AI generates. Ali, how is
it now, can we say that it is the best method?
```d
import core.thread;
import core.atomic;
import core.sync.mutex;
struct GlobalCounter
{
private Mutex mutex;
private shared int gInt;
void initialize(int initialValue = 0)
{
mutex = new Mutex();
gInt = initialValue;
}
void increment(int value)
{
synchronized(mutex)
{
gInt.atomicOp!"+="(value);
}
}
auto getValue()
{
synchronized(mutex)
{
return gInt;
}
}
}
enum INC = 100;
void incrementInThread(int incrementValue)
{
for (int i = 0; i < INC; i++)
{
globalCounter.increment(incrementValue);
}
}
__gshared GlobalCounter globalCounter;
void main()
{
globalCounter.initialize(41);
auto threads = [
new Thread(() { incrementInThread(1); }),
new Thread(() { incrementInThread(2); }),
new Thread(() { incrementInThread(3); })
];
foreach (ref thread; threads)
{
thread.start();
thread.join();
}
assert(globalCounter.getValue == 641);
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list