How to access local storage using pthreads

I have code that is completely parallel, no dependencies, so using pthreads was a natural choice. Unfortunately, there is one common resource, the log file.

We don’t want the log to be alternated in turn anyway, so instead of using mutexes for each log call, I want to open a separate log file for each thread. But at present, through all the code, there is a global variable logger.

I currently have two solutions, none of which make me happy.

  • Implement a hash on the thread id: pthread_self ().
  • Pass a parameter from creating the thread for each function that it calls (very invasive).

I would like some smart way to make it look like I have a global variable in each thread, something with very little overhead.

+4
source share
3 answers

If each thread receives its own log, use pthread_key_create and related functions to maintain the thread logger variable.

+4
source

There is a standard way of processing such variables for each line: pthread_key_create and company.

If you just like gcc and its extensions, they have the __thread keyword for storing threads.

+4
source

Good fix : no longer use a global variable, and each thread has its own logging object.

Quick fix . Convert the global variable logger to a macro that expands in a call to the logging function, passing the stream identifier. Or, use pthreads native local storage capabilities (see pthread keys).

So let's say you have:

 log(global_fd, char* entry); 

You can not change every time this happens:

 #define global_fd get_thread_fd() 

And voila!

+2
source

All Articles