Local Stream and Context Switch

I have some C ++ code using thread local storage, each thread has a vector into which it can insert data.

I am using TLS to store the id of the index in a stream, this can be used to find which vector to enter data. It then executes enough code to push the data into a vector.

I am wondering if it is possible that the OS could reschedule my code to run on a different thread after it has acquired a pointer to a thread local object. (So ​​far, the code runs fine, and I haven't seen it.) But if it were possible, it would seem to break my program, as it would now be possible for two threads to have the same object.

Assuming this is true, it looks like it will be a problem even for any code that uses TLS of any complexity, is TLS only for simple objects where you don't take an address?

Thank!

+3


source to share


2 answers


Local thread storage is only storage per thread. Each stream has its own data structure. This thread, depending on which processor it is running on, is the same thread. The OS does not schedule the WITHIN threads, it schedules which thread is running.

Thread local storage is accomplished with some indirection that changes with the thread itself. There are several ways to do this, for example the OS can have a specific page at a specific offset from the start of virtual memory in the process, and when a thread is scheduled, the page table is updated according to the thread.



In x86 processors FS or GS are usually used for data "on the stream", so the OS will toggle the FS register [or the contents of the base address of the register in the case of 64-bit processors]. When reading TLS, the compiler will use the FS or GS segment register to prefix read / write operations in memory, so you always get "your private data" and not some other streams.

Of course, the OS can have bugs, but something has a lot to rely on, so if it breaks it will show up pretty soon (unless it is very thin and you have to stand on the right side, with the moon in the right phase, wearing correct clothes colors and wind in the right direction, date divisible by 3 and 7, etc. etc.).

+2


source


TLS means stream local , from your description each stream accesses a common vector of the vector via TLS (I'm not sure), you must use some kind of lock. Any code examples?



+2


source







All Articles