Re:Don't setenv in multi-threaded code on glibc
by jwilk on Tuesday January 31, 2017 @07:07AM
(#13529846)
If setenv() is not thread-safe, then why is it using locks?
[ Parent
| on HN ]
Re:Don't setenv in multi-threaded code on glibc
by kelnos on Tuesday January 31, 2017 @07:30AM
(#13529943)
setenv() is indeed thread-safe. getenv() is not. That is, you can end up in the following situation:
1. thread1 calls getenv() and gets a pointer to a section of environ A
2. thread2 calls setenv() & acquires lock & allocs environ B & frees environ A & releases lock
3. thread1 tries to look at the pointer in environ A, and crashes because environ A has been freed
Now, if you never call getenv(), and just call setenv() from multiple threads, that's safe, because setenv() itself is thread-safe. It's the combination that kills you.