chenBright commented on code in PR #3713:
URL: https://github.com/apache/brpc/pull/3713#discussion_r4481374858


##########
src/butil/thread_local.h:
##########
@@ -29,6 +30,34 @@
 #define BAIDU_THREAD_LOCAL __thread
 #endif  // _MSC_VER
 
+// Define a pthread-local variable accessed through name():
+//   BUTIL_THREAD_LOCAL(int, counter, 0);
+//   ++counter();
+//   counter() = 10;
+// Prefix with static for internal linkage or a static class member, or inline
+// for a definition in a header. A declaration in another translation unit is
+// simply `type& name();`. Use a type alias for arrays or types containing 
commas.
+//
+// A bthread can resume on a different pthread. Keep TLS address resolution in
+// a non-inlined function so the compiler cannot hoist it across a suspension.
+// The opaque asm output also prevents interprocedural optimization (including
+// LTO) from treating the returned address as invariant. A memory barrier 
alone,
+// or an inline function taking &tls as its argument, does not achieve this.
+//
+// The returned reference/pointer is only valid for the current pthread: never
+// retain it across a call that may suspend. In particular, evaluate a possibly
+// suspending RHS before assigning it to name(). Initializers must not suspend.
+// Constant-initialized trivial types have no dynamic initialization/exit hook.
+#define BUTIL_THREAD_LOCAL(type, name, ...)                                  \
+    __attribute__((noinline, unused)) type& name() {                          \
+        static thread_local type tls_value = __VA_ARGS__;                    \
+        type* tls_ptr = std::addressof(tls_value);                            \
+        asm volatile("" : "+r"(tls_ptr) : : "memory");                       \
+        return *tls_ptr;                                                     \
+    }

Review Comment:
   Windows/MSVC support is outside the scope of this PR. The implementation 
targets GCC and Clang, consistent with brpc's supported build configurations. 
We will keep the current implementation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to