简体   繁体   English

static 自由函数线程安全吗?

[英]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.我正在编写一个多线程程序,并且有一个 function 将从多个线程调用,该线程是一个 cpp 文件中的 static 免费 function。 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.这个 function 永远不会从 cpp 文件外部调用,所以我想将其设为 static 以便它具有内部链接。

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.谷歌搜索我发现很多人说“静态函数不是线程安全的”但是当我 go 阅读它时,每个人似乎都在谈论 static 成员函数,而不是 ZA81259CEF8E959C624DF1D456E

Are static free functions thread safe (assuming they don't access any shared state between threads)? static 自由函数是否线程安全(假设它们不访问线程之间的任何共享 state)?

Any function that accesses no shared state is inherently thread safe.任何不访问共享 state 的 function 本质上都是线程安全的。 You only get a data race when you have unprotected read/writes to shared state.只有当您对共享 state 进行未受保护的读/写操作时,您才会遇到数据竞争。 If there is no shared state, you can't have a data race.如果没有共享的 state,则不能进行数据竞争。

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.如果 function 没有副作用,那么您可以在任意数量的线程中调用它。

Static functions are the same as other functions. Static 功能与其他功能相同。 It is not the function, it is what the function does.这不是 function,而是 function 所做的。

I think some people are mixing between terms.我认为有些人在术语之间混淆。 static function vs function with static variables. static function 与 function 与 ZA81259CEF8E959C2297DF1D456E5D 变量。

while static function may be safe or not, a function with static variables is not safe without synchronization.虽然 static function 可能安全与否,但带有 ZA81259CEF8565D 变量的 function 是不安全的。

An example of such a function is strtok which keeps in a static variable the continuation point.这种 function 的一个示例是strtok ,它在 static 变量中保存连续点。 when several threads use the old strtok , it may cause a mixture between the inputs.当多个线程使用旧的strtok时,可能会导致输入之间的混合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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