Thread-safety vs atomicity in C

As far as I know, thread-safe functions can be called without needing to mutex or semaphore. Can't they?

For example, strcpy() or strdup() is kinda thread safe function.

But when I was reading the man-page, I saw the following and don't understand the saying along with the bolded example.

Being MT-Safe does not imply a function is atomic, nor that it uses any of the memory synchronization mechanisms POSIX exposes to users. It is even possible that calling MT-Safe functions in sequence does not yield an MT-Safe combination. For example, having a thread call two MT-Safe functions one right after the other does not guarantee behavior equivalent to atomic execution of a combination of both functions, since concurrent calls in other threads may interfere in a destructive way.

Is the following usage wrong in a thread's function? If yes, what are the wrong points? If no, what is the meaning of quoted saying with the bolded one?

char *s1 = calloc(14, 1);
char *s2 = calloc(6, 1);
char *s3 = strdup("soner");
char *s4 = strdup("stackoverflow");
strcpy(s2, s3);
strcpy(s1, s4);
s1[13] = s2[5] = 0;

mutex_lock(&mtx);
printf("%s %s", s1, s2);
fflush(stdout);
mutex_unlock(&mtx);

free(s1);
free(s2);
free(s3);
free(s4);

Upvotes: 2

Views: 1033

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

"MT-Safe" in this context only means that you can call the function from multiple threads, not that there's any synchronization between the threads.

For example, you have two threads where one is doing strcpy(s1, "foo") and the other is doing strcpy(s1, "bar") (and s1 is a buffer shared between the threads), then you have a data-race as both threads could attempt to write to the destination s1 simultaneously.

Upvotes: 6

Related Questions