Synchronisation help
Anonymouse
zorael at gmail.com
Mon Jan 1 15:48:16 UTC 2024
I have a `shared string[int]` AA that I access from two different
threads. The function I spawn to start the second thread takes
the AA as an argument.
```d
class Foo
{
shared string[int] bucket;
Tid worker;
}
void workerFn(shared string[int] bucket)
{
while (true)
{
// occasionally reads, occasionally modifies bucket
}
}
void main()
{
auto foo = new Foo;
foo.bucket[0] = string.init;
foo.bucket.remove(0);
foo.worker = spawn(&workerFn, foo.bucket);
while (true)
{
// occasionally reads, occasionally modifies bucket
}
}
```
(`run.dlang.io` shortening seems broken again, but I made a
[gist](https://gist.github.com/zorael/17b042c424cfea5ebb5f1f3120f983f4) of a more complete example.)
Reading the specs on `synchronized` statements, it seems I need
to provide an `Object` to base synchronisation on when two
*different* places in the code needs synchronising, whereas if
it's in the same place an expressionless `synchronize { }` will
do.
The worker function can't see `Foo foo` inside `main`, so it
can't share synchronisation on that.
What is the common solution here? Do I add a module-level `Object
thing` and move everything accessing the AA into
`synchronized(.thing)` statements? Or maybe add a `shared static`
something to `Foo` and synchronise with `synchronize(Foo.thing)`?
More information about the Digitalmars-d-learn
mailing list