parthi_for_tech
parthi_for_tech

Reputation: 49

Is shared library local variable thread safe?

I'm developing a multi-threaded application which application which will access a shared library, now i see that the shared library doesn't contain any global variable, so does it mean that the library is thread safe? for example.

I'm calling function func() from various threads to a shared library like:

thread 1 -> func()

thread 2 -> func()

...

thread N ->func()

and the func() is defined as below,

void func(){
    int var;
    func2(&var);
}

In this cases, will it be thread safe?

Upvotes: 0

Views: 1868

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The usage that you are showing is thread-safe, because invocations of func from each thread will have their own copy of the variable var.

This is not a guarantee, though, for several reasons:

  • Library needs to be careful about its use of static variables as well. If you replace int var with static int var, func would not longer be thread-safe
  • You need to be careful about calling the library. If the same pattern that you show is present in your code, i.e. if your code shares a local variable among threads, the code would not be thread-safe.
  • The library may use functions that are not thread-safe, such as strtok. Using these functions makes your library not thread-safe.

Upvotes: 1

unwind
unwind

Reputation: 399703

Yes, the code in question will execute in the context of each thread, and the local automatic variable will typically be stored on each thread's stack.

Upvotes: 1

Related Questions