Linux strtok 函数线程安全
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4031075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
strtok function thread safety
提问by Steveng
I have been spending some time in debugging a programme which gives segmentation fault. The bug is quite indeterministic and intermittent, which is annoying. I narrowed it down to the calling of strtok()
. I suspect that it is the calling of strtok()
to split string in two different threads that causes the segmentation fault. Can I call strtok()
in two different threads?
我花了一些时间来调试一个导致分段错误的程序。该错误非常不确定且断断续续,这很烦人。我将范围缩小到调用strtok()
. 我怀疑是strtok()
在两个不同的线程中调用拆分字符串导致了分段错误。我可以调用strtok()
两个不同的线程吗?
Thanks.
谢谢。
采纳答案by Puppe
strtok()
is not reentrant so it should not be used from threaded applications, use strtok_r()
instead.
strtok()
不可重入,因此不应从线程应用程序中使用它,而应使用它strtok_r()
。
回答by Benoit Thiery
strtok()
is not MT-safe because it stores some intermediate variables globally and reuse them at each call (see you don't have to pass again the string each time you call strtok()
).
You can have a look at the man pages of methods you are using and it is always indicated at the end if it is MT-safe or not.
strtok()
不是 MT 安全的,因为它全局存储一些中间变量并在每次调用时重用它们(看到每次调用时都不必再次传递字符串strtok()
)。您可以查看您正在使用的方法的手册页,并且总是在末尾指出它是否是 MT 安全的。
When a method is not MT-safe (multi-thread safe or reentrant), you should look for same method with suffix _r meaning reentrand. In your example, strtok_r()
as suggested in the other answer.
当一个方法不是 MT 安全的(多线程安全或可重入的)时,您应该寻找带有后缀 _r 表示可重入的相同方法。在您的示例中,strtok_r()
正如其他答案中所建议的那样。