Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define thread safe array?

How can I define a thread safe global array with minimal modifications?

I want like every access to it to be accomplished by using mutex and synchronized block.

Something like this as 'T' will be some type (note that 'sync' keyword is not currently defined AFAIK):

sync Array!(T) syncvar;

And every access to it will be simmilar to this:

Mutex __syncvar_mutex;

    //some func scope....
    synchronized(__syncvar_mutex) { /* edits 'syncvar' safely */ }
like image 692
AnArrayOfFunctions Avatar asked Apr 22 '15 19:04

AnArrayOfFunctions


1 Answers

My naive attempt was to do something like this:

import std.typecons : Proxy:

synchronized class Array(T)
{
    static import std.array;
    private std.array.Array!T data;
    mixin Proxy!data;
}

Sadly, it doesn't work because of https://issues.dlang.org/show_bug.cgi?id=14509

Can't say I am very surprised though as automagical handling of multi-threading via hidden mutexes is very unidiomatic in modern D and the very concept of synchronized classes is mostly a relict from D1 times.

You can implement same solution manually, of course, by defining own SharedArray class with all necessary methods and adding locks inside the methods before calling internal private plain Array methods. But I presume you want something that work more out of the box.

Can't invent anything better right here and now (will think about it more) but it is worth noting that in general it is encouraged in D to create data structures designed for handling shared access explicitly instead of just protecting normal data structures with mutexes. And, of course, most encouraged approach is to not shared data at all using message passing instead.

I will update the answer if anything better comes to my mind.

like image 96
Mihails Strasuns Avatar answered Oct 07 '22 00:10

Mihails Strasuns