Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are strtol, strtoll, strtod really thread safe?

Tags:

c++

I know how to convert a string into int, float... is never a new question. After going through some articles, I was suggested to use strtol, strtoll, strtod, so I took a close look at those functions.

Although strtol claims thread safety in its man page, but it will modify errno, so does it really thread safe?

If not, what's the right way to do such converting jobs in C++ (not C++11) and keep thread safe?

like image 530
coinsyx Avatar asked Mar 07 '14 10:03

coinsyx


People also ask

What does strtol return if fails?

The strtol() function returns the result of the conversion, unless the value would underflow or overflow. If an underflow occurs, strtol() returns LONG_MIN. If an overflow occurs, strtol() returns LONG_MAX. In both cases, errno is set to ERANGE.

What is strtol base?

endptr : A pointer used by strtol , which points to the first non-integer character signaled to stop conversion. base : The base of the number being converted. It must be between 2 and 32, inclusive, or be a special value 0.

How strtol works?

The strtol() function converts a character string to a long integer value. The parameter nptr points to a sequence of characters that can be interpreted as a numeric value of type long int. The strtoll() function converts a character string to a long long integer value.

Is strtol fast?

strtol() (and its family) is the safest standard one and also a very fast one, but it is incredibly difficult to use, so I decided to write a safe and simple interface to it.


2 Answers

From the errno man page:

errno is defined by the ISO C standard to be a modifiable lvalue of type int, and must not be explicitly declared; errno may be a macro. errno is thread-local; setting it in one thread does not affect its value in any other thread.

A function that sets errno will only set it for a single thread, so it's thread-safe.

like image 97
user2357112 supports Monica Avatar answered Sep 28 '22 01:09

user2357112 supports Monica


Yes they are, since errno itself is not a plain ordinary global variable: errno is thread-safe.

This is answered in Is errno thread-safe?.

like image 35
unwind Avatar answered Sep 28 '22 00:09

unwind