Thibaud Auzou
Thibaud Auzou

Reputation: 139

Is A Member Function Thread Safe?

I have in a Server object multiple thread who are doing the same task. Those threads are init with a Server::* routine.

In this routine there is a infinite loop with some treatments.

I was wondering if it was thread safe to use the same method for multiple threads ? No wonder for the fields of the class, If I want to read or write it I will use a mutex. But what about the routine itself ?

Since a function is an address, those thread will be running in the same memory zone ?

Do I need to create a method with same code for every thread ?

Ps: I use std::mutex(&Server::Task, this)

Upvotes: 7

Views: 1969

Answers (4)

There is no problem with two threads running the same function at the same time (whether it's a member function or not).

In terms of instructions, it's similar to if you had two threads reading the same field at the same time - that's fine, they both get the same value. It's when you have one writing and one reading, or two writing, that you can start to have race conditions.

Upvotes: 5

MSalters
MSalters

Reputation: 179991

Behind the scenes, int Server::Task(std::string arg) is very similar to int Server__Task(Server* this, std::string arg). Just like multiple threads can execute the same function, multiple threads can also execute the same member function - even with the same arguments.

A mutex ensures that no conflicting changes are made, and that each thread sees every prior change. But since code does not chance, you don't need a mutex for it, just like you don't need a mutex for string literals.

Upvotes: 0

user349594
user349594

Reputation:

While the function itself might be the same address in memory in terms of its place in the table you aren't writing to it from multiple locations, the function itself is immutable and local variables scoped inside that function will be stacked per thread.

If your writes are protected and the fetches don't pull stale data you're as safe as you could possibly need on most architectures and implementations out there.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522084

In C++ every thread is allocated its own call stack. This means that all local variables which exist only in the scope of a given thread's call stack belong to that thread alone. However, in the case of shared data or resources, such as a global data structure or a database, it is possible for different threads to access these at the same time. One solution to this synchronization problem is to use std::mutex, which you are already doing.

Upvotes: 4

Related Questions