Gilgamesz
Gilgamesz

Reputation: 5073

Initialization before we start a multithreading code

int main(){
    // X is a shared resource
    initSharedResourceX();
    startMultitreadingServer(); // handle requests concurrently with function handle() <- below. All handlers (run concurrently) access to X **read-only**.


}

int handle(){
    return X.get(); // get() is read-only
}

I would like to avoid synchronization access to X by initialization a shared resource before we start. Do I need a compiler barrier? I can imagine that a compiler do someting like:

int main(){
    startMultitreadingServer(); 
}

int handle(){
    if(X is not initialized) {
        initSharedResourceX();
    }
    return X.get(); 
}

and as we can see it breaks our program.

I know, the compiler must be super-smart to do it. Especially, the compiler must know what does it mean to initialize X. So, it must really super-super-smart. But, can we assume that it is not?

What do you think?

Upvotes: 0

Views: 75

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 66153

If a compiler doesn't see the code of startMultitreadingServer function, then it is prohibited (by a language specification) to move any code around an invocation of the function.

If a compiler see the code of startMultitreadingServer function, then it should found a memory barrier (or any operation which cause this effect) inside the function. (Any thread-starting function should have a memory barrier inside; this should be stated in its contract/description). And again, the compiler cannot move (at least, forward) any code around this barrier.

So, in any case a compiler cannot move the code, preceding the thread-creation function call, after that call.

Upvotes: 1

Related Questions