On Thursday, 9 June 2016 at 18:31:16 UTC, cy wrote:
I was thinking of using threads in a D program (ignores
unearthly wailing) and I need 1 thread for each unique string
resource (database connection info). So I did this:
shared BackgroundDB[string] back;
I don't see any way to make less data shared there. If it
weren't shared, it would be thread local, and two application
threads trying to look up the same database would end up firing
off two BackgroundDB threads, since they had separate copies of
"back" that could not share keys. So it pretty much has to be
shared. But that means freaking /everything/ has to be shared.
In the dedicated thread, I had it repeatedly waiting on a
condition, and once that condition is signaled, it removes
what's been queued up, and processes those queued items in the
database. Except for one problem... conditions can't be shared.
Error: non-shared method core.sync.condition.Condition.mutex
is not callable using a shared object
Obviously you shouldn't need mutexes if you're using shared...
but how do you do conditions, then?
When I do something like this:
struct BackgroundDB {
Condition stuff_ready;
...
}
Condition is implicitly converted to shared(Condition) when I
create a shared(BackgroundDB), and BackgroundDB is implicitly
converted to shared(BackgroundDB) when I have a shared
BackgroundDB[string]. But shared(Condition) then has a
shared(Mutex) inside it, and that can't be locked, since
Mutex.lock is a non-shared function.
Is core.sync.mutex.Mutex even usable in D anymore? It seems
every mutex that wasn't shared would be part of thread local
data, so two threads locking on the same mutex would actually
be locking separate mutexes.
Mutex, Condition, and Thread classes should be defined as shared
as you experience, but they are not unfortunately. What you need
to do is the define them as shared, and while calling their
method, remove shared from them. Example is below:
class MyClass{
private core.sync.mutex.Mutex mx;
public this() shared{
mx = cast(shared)( new core.sync.mutex.Mutex() );
(cast()mx).lock();
... etc.
}
}