Multithreading global static variables

I have global static variables in the C library that throw exceptions in a multi-threaded run. I need to somehow make them safe (i.e., each thread must relate to another instance of these variables). Any recommended methods?

+4
source share
4 answers

There is no standard way that works in all C implementations, but there are implementation-specific solutions. For example, with the Microsoft compiler (see documents ),

__declspec( thread ) int tls_i = 1; 

makes tls_i live in streaming local storage (each thread has its own separate instance of this variable). With gcc syntax

 __thread int tls_i; 

You can also check the Wikipedia entry for this.

+9
source

First question:

  • Do threads need their own copies of variables?
  • or do they need to coordinate access to one shared copy?

If you need the first one, other answers have made suggestions about "streaming local storage."

If you need the latter, somehow you need to provide the appropriate mutex for these variables (the size of the mutex is one of the problems you are facing), and that all threads use the mutex and free the mutex. This is harder. Perhaps even you need to provide functions that control access to variables.

The errno standard variable can be a variable:

 extern int *_errno_func(void); #define errno (*(_errno_func)()) 

In a multi-threaded application (compiled with -DREENTRANT) this happens; on MacOS X, this is similar to what happens anyway (they use the name __error instead of _errno_func , both are in the implementation namespace).

You may want to or do something similar for your variables. The fact that you say that they are static improves the situation a bit. You have only one file to consider (unless you are too careful to pass back or pointers to these variables).

+4
source

You will need TLS (local stream storage) , which is also known as stream - dependent data or stream - dependent data . This mechanism can ensure that each thread gets access to its own separate copy of the data, without worrying about synchronizing access with other threads.


There are two ways to use TLS:

  • implicitly: using the keyword

    Windows: __declspec (thread) int tls_var = 10;

    Linux with GCC: __thread int tls_var = 10

  • Explicit: Using the TLS-specific API

    Window:

    TlsAlloc (): allocates memory for tls data
TlsFree (): free tls data memory TlsSetValue (): set tls value TlsGetValue (): get tls value

See MSDN for more details.

LInux with GCC:

pthread_key_create () : create data tls pthread_key_delete () : delete data tls pthread_getspecific () : get the value tls pthread_setspecific (): set the value tls Go to the manpage for specific and detailed information.
+3
source

Most compilers have a certain way of defining a local thread store. Assuming this is available, what you want.

+1
source

Source: https://habr.com/ru/post/1307272/


All Articles