is sprintf thread safe?

2020-07-06 09:02发布

is sprintf thread safe ?

//Global log buffer 
char logBuffer[20];

logStatus (char * status, int length)
{
  snprintf(logBuffer, 19, status);
  printf ("%s\n", logBuffer);
}

The thread safety of this function totally depends upon the thread safety of snprintf/sprintf .

Updates : thanks for ur answers . i dont mind, if the actual contents gts messed up. but want to confirm that the sprintf would not cause a memory corruption / buffer overflow going beyond 20 bytes in this case, when multiple threads are trying to write to logBuffer ?

7条回答
Root(大扎)
2楼-- · 2020-07-06 09:52

Regarding your update about not worrying if the logBuffer content get garbled:

I'm not sure why you want to avoid making your function completely thread safe by using a locally allocated buffer or some synchronization mechanism, but if you want to know what POSIX has to say about it, here you go (http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11):

Applications shall ensure that access to any memory location by more than one thread of control (threads or processes) is restricted such that no thread of control can read or modify a memory location while another thread of control may be modifying it. Such access is restricted using functions that synchronize thread execution and also synchronize memory with respect to other threads. [followed by a list of functions which provide synchronization]

So, POSIX says that your program needs to make sure mutilple threads won't be modifying logBuffer concurrently (or modifying logBuffer in one thread while reading it in another). If you don't hold to that, there's no promise made that the worst that will happen is garbled data in logBuffer. There's simply no promise made at all about what the results will be. I don't know if Linux might document a more specific behavior, but I doubt it does.

查看更多
登录 后发表回答