简体   繁体   中英

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.

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.

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.

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.
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 .

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

There is a list of thread-unsafe functions in POSIX. Accordingly to it at least on POSIX strcmp() would be thread-safe.

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