Search code examples
cthread-local-storage

Any size limit on the __thread buffer?


I want to use a buffer on the level of thread. But I think malloc/free in every function is boring. They can share the buffer.

static __thread char my_buff[BUF_SIZE] = {0};

But is there any size limit on this buffer? If there is, how to check it?


Solution

  • thread_local objects are dynamically allocated when a thread is created (or at any rate before the object is used, courtesy of the "as-if" clause). Nothing in the C standard specifies how the allocation is done, but on many systems the standard library's dynamic allocation functions are used. So there is probably no limit as long as dynamically allocated memory is available. (The standard also doesn't say anything about when this storage is returned to whatever storage manager allocated it; it is certainly possible to imagine an implementation which does not return thread local segments until the application terminates, preferring to recycle segments from terminated threads to newly-created ones. But I don't believe that's common.)

    Note that at least on statically-linked executables, thread-local objects are allocated for every thread, whether or not the thread uses the object. Modules which are dynamically loaded can also include thread-local objects, so the amount of thread-local storage needed for a thread can change as modules are loaded and unloaded. The implementation of this feature requires an extra level of indirection accessing thread-local storage, and also commonly involves lazy allocation of TLS segments (not individual objects).

    I really only have experience with ELF systems; I searched a bit in the usual places to verify that thread_local should work in roughly the same way on modern Windows. Legacy platforms may not have the feature, so you might be limiting portability by using it. I wouldn't normally let that stop me, but it does seem prudent to check the platform documentation for platforms which you intend to support.