次の方法で共有


Fiber/Thread Local Storage

Over the course of professional development you run into extremely helpful functions in the Windows API.  Today I ran into a set of functions that allow for storing a value specific to each thread.  See the following link for a description of how to use thread local storage.

https://msdn.microsoft.com/en-us/library/windows/desktop/ms686991(v=vs.85).aspx

Note that a fiber runs in the context of the scheduling thread.  Each thread may have multiple fibers and each fiber may have its own local storage.  If a thread only has one fiber, then thread and fiber local storages are identical.  For more information about fibers:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682661(v=vs.85).aspx

Now, to the more interesting part, using the APIs.  Luckily, using the local storage is straight forward.

Process for using a local storage:

  1. Initialize local storage to retrieve index using TlsAlloc()
  2. Set values in local storage using TlsSetValue()
  3. Retrieve values using TlsGetValue()

Allocate the thread local storage once for all threads.  Each thread uses the same index to set and retrieve values.

The first MSDN link has a great explanation on thread local storage.