简体   繁体   中英

Are static free functions thread safe?

I am writing a multithreaded program and have a function that will be called from multiple threads that is a static free function within a cpp file. This function will never be called from outside of the cpp file so I wanted to make it static so that it had internal linkage.

Googling around I found a lot of people saying "static functions are not thread safe" but then when I go to read up about it everyone seems to be talking about static member functions, not static free functions.

Are static free functions thread safe (assuming they don't access any shared state between threads)?

Any function that accesses no shared state is inherently thread safe. You only get a data race when you have unprotected read/writes to shared state. If there is no shared state, you can't have a data race.

This is why purely functional languages are naturally thread safe. If a function doesn't have side effects, then you can call it in as many threads as you want.

Static functions are the same as other functions. It is not the function, it is what the function does.

I think some people are mixing between terms. static function vs function with static variables.

while static function may be safe or not, a function with static variables is not safe without synchronization.

An example of such a function is strtok which keeps in a static variable the continuation point. when several threads use the old strtok , it may cause a mixture between the inputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM