Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 616
Thibaud Auzou Avatar asked Jul 15 '15 00:07

Thibaud Auzou


1 Answers

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.

like image 76
user253751 Avatar answered Sep 21 '22 09:09

user253751