简体   繁体   English

strcmp 是线程安全的吗?

[英]Is it thread-safe to strcmp?

strcmp(variable, "constant");

还是我必须用互斥锁来保护它?

If variable can be modified by other thread you must protect it.如果变量可以被其他线程修改,你必须保护它。 No magic here – higher level languages could do such function call atomically and that is the 'magic' not present in C.这里没有魔法——高级语言可以原子地执行这样的函数调用,这就是 C 中不存在的“魔法”。

Please note that protection (by a single lock) need both the 'variable' pointer value (address of the string in the memory) and the string itself (note: it could be referenced by other pointer too).请注意,保护(通过单个锁)需要“变量”指针值(内存中字符串的地址)和字符串本身(注意:它也可以被其他指针引用)。 If the string is modified while 'strcmp' is running you could get false result or a buffer overflow and a segmentation fault.如果在“strcmp”运行时修改了字符串,您可能会得到错误结果或缓冲区溢出和分段错误。

Locks protect data, not code.锁保护的是数据,而不是代码。

Since strcmp has no way of knowing what lock you might be using to protect variable , there's no way it could possibly acquire that lock, so the function is not "thread-safe" in the sense you probably mean.由于strcmp无法知道您可能使用什么锁来保护variable ,因此它不可能获得该锁,因此该函数在您可能的意思上不是“线程安全的”。

You need to protect access to variable if it is shared.如果变量是共享的,则需要保护对变量的访问。
Multiple threads calling strcmp is safe by itself (functionality wise) since, strcmp just compares the 2 strings and does no modification.多个线程调用 strcmp 本身是安全的(功能方面),因为 strcmp 只比较两个字符串并且不做任何修改。
But since the variable could have been changed by other thread while strcmp is running, modification could break strcmp during its operation so you should guard it along with all the other places you access variable .但是由于在 strcmp 运行时该variable可能已被其他线程更改,因此修改可能会在其操作期间破坏 strcmp ,因此您应该保护它以及您访问variable所有其他地方。

It's safe.它是安全的。 The parameters and any internal variables go on the stack so are different memory to any other threads that may be calling the same function.参数和任何内部变量都在堆栈上,因此与可能调用同一函数的任何其他线程不同的内存。

Look here: http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_09.html看这里: http : //www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_09.html

There is a list of thread-unsafe functions in POSIX. POSIX 中有一个线程不安全函数列表。 Accordingly to it at least on POSIX strcmp() would be thread-safe.因此,至少在 POSIX strcmp()上它是线程安全的。

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

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