strtok function thread safety
Asked Answered
S

2

20

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?

Thanks.

Swadeshi answered 27/10, 2010 at 8:4 Comment(1)
Please do not tag a question C++ when it is actually a C question.Sepia
I
38

strtok() is not reentrant so it should not be used from threaded applications, use strtok_r() instead.

Infirmary answered 27/10, 2010 at 8:7 Comment(2)
I tried using Dev-C++ to make a C program, and strtok_r wasn't available :( I'm not sure what standard/version/compiler devcpp usesAmenra
The POSIX standard version of strtok has an extra pointer. where it can keep the state. So that version is thread-safe as long as different treads using different pointers.Stine
P
8

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.

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.

Peccant answered 27/10, 2010 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.