Commit 0347a79f authored by Alexander Shaposhnikov's avatar Alexander Shaposhnikov Committed by facebook-github-bot-4

Fix a bad bug in folly::ThreadLocal (incorrect using of pthread)

Summary: Fix incorrect using of pthread in folly::ThreadLocal.

The root of the trouble (see man pthread_key_create):
"At thread exit, if a key value has a non-NULL destructor pointer,
and the thread has a non-NULL value associated with that key,
the value of the key is set to NULL, and then the function pointed to is called
with the previously associated value as its sole argument."

At thread exit we need to recover the thread-specific threadEntry
otherwise the subsequent calls of getThreadEntry may recreate it
(what actually DOES  happen in the test ThreadLocalPtr.CreateOnThreadExit)
and the newly created threadEntry will "leak". It will live longer than the corresponding
thread violating the internal invariant of StaticMeta and also it will break
the code of the method onThreadExit. In particular this bug causes the failure
of the test ThreadLocalPtr.CreateOnThreadExit on OSX.

Reviewed By: @lbrandy

Differential Revision: D2304950
parent cbaaa2db
...@@ -267,6 +267,12 @@ struct StaticMeta { ...@@ -267,6 +267,12 @@ struct StaticMeta {
DCHECK_EQ(ptr, &meta); DCHECK_EQ(ptr, &meta);
DCHECK_GT(threadEntry->elementsCapacity, 0); DCHECK_GT(threadEntry->elementsCapacity, 0);
#else #else
// pthread sets the thread-specific value corresponding
// to meta.pthreadKey_ to NULL before calling onThreadExit.
// We need to set it back to ptr to enable the correct behaviour
// of the subsequent calls of getThreadEntry
// (which may happen in user-provided custom deleters)
pthread_setspecific(meta.pthreadKey_, ptr);
ThreadEntry* threadEntry = static_cast<ThreadEntry*>(ptr); ThreadEntry* threadEntry = static_cast<ThreadEntry*>(ptr);
#endif #endif
{ {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment