Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do i need a mutex for a static function?

I have a C++ class with a static function:

class Foo
{
public:
    static void bar(int &a)
    {
        a++;
    }
}

EDIT:
The variable passed as argument is only used within the calling scope. So it is not accessed by another thread.

Do i have to use a mutex when i call this function from a seperate thread?

Thanks.

like image 948
daB0bby Avatar asked Mar 16 '26 08:03

daB0bby


2 Answers

Calling this function requires only thread-local resources, the stack of thread. Therefore the answer is no. If the int variable is accessible by more than the calling thread, you will need a mutex for the variable

like image 91
user6176790 Avatar answered Mar 17 '26 22:03

user6176790


Whether a function is static has no bearing on whether calls to it need to be synchronised.

The determining factor is whether the function is re-entrant, and what you do with the data. In this case, the function is re-entrant (as it has no non-local state of its own, or in fact any state at all), and the data is owned/managed by the calling scope, so you will have to decide within the calling scope whether that integer requires protection.

But this is true whether bar is a static member, a non-static member, a free function, a macro, a cat, a black hole, or Jon Skeet's tumble dryer.

like image 34
Lightness Races in Orbit Avatar answered Mar 17 '26 22:03

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!