Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FLS vs TLS, can I use Fiber Local Storage in place of TLS?

I have portable TLS (thread local storage) code in my library for win-threads and for pthreads, but TlsXXX api isn't available on WinRT. However, there is FlsXXX api that serves almost the same purpose as the TLS api. From MSDN:

A fiber can use fiber local storage (FLS) to create a unique copy of a variable for each fiber. If no fiber switching occurs, FLS acts exactly the same as thread local storage

So, does that mean I can simply use FlsXXX api as a drop-in replacement (I don't use fibers, and I don't use __thread specifiers for variables, I use the api directly).

like image 677
Pavel P Avatar asked Oct 26 '13 23:10

Pavel P


1 Answers

First you have to convert the thread to a fiber.

Which you cannot do in a Store app, nice chicken-and-egg problem. It is what the SDK docs say but that's not actually what the Microsoft CRT does, it uses FlsAlloc() but never calls ConvertThreadToFiber/Ex() anywhere. So you're okay, just never call CreateFiber().

And yes, FLS is identical to TLS if you don't create fibers according to the SDK:

A fiber can use fiber local storage (FLS) to create a unique copy of a variable for each fiber. If no fiber switching occurs, FLS acts exactly the same as thread local storage. The FLS functions (FlsAlloc, FlsFree, FlsGetValue, and FlsSetValue) manipulate the FLS associated with the current thread. If the thread is executing a fiber and the fiber is switched, the FLS is also switched.

You can also see that being used in the CRT, take a look at the VS2012+ vc/crt/src/Platform.cpp source code file, __TlsAlloc() function. You see it fallback to FlsAlloc when _CRT_APP is #defined. It is for the VCLibs build, the one that's used in Store apps.

Not documented explicitly but very strong proof that this is just fine.

like image 112
Hans Passant Avatar answered Oct 09 '22 23:10

Hans Passant