drh/cii

Is the Except lib tread safe ?

GoogleCodeExporter opened this issue · 3 comments

Hi,

Is the Except lib tread safe ?

I have a multithreaded app, i really like your small Except lib but is it safe ?

Thanks,
Alex

Original issue reported on code.google.com by ealexs on 14 Feb 2011 at 10:21

No, Except is not thread safe, because it uses a global static variable, 
Except_stack. To be thread-safe, Except_stack would need to be a thread-local 
static variable. The WIN32 version (i.e., the code protected by #ifdef WIN32) 
attempts to use thread-local storage for this purpose.

It might be possible to make Except thread safe by protecting access to 
Except_stack with a mutex.

Original comment by drhan...@gmail.com on 15 Feb 2011 at 6:42

  • Changed state: Done
  • Added labels: Type-Other
  • Removed labels: Type-Defect
Thanks, I will try to find a way to set a "thread-local" variable probably 
based on the thread ID. I would like to avoid a mutex as they are a bit slow 
under windows :(

Thanks again,
Alex

Original comment by ealexs on 16 Feb 2011 at 7:47

Back ;)

So to make it thread safe (in case anyone needs to):

A. GNU Compiler (including MingW)

// WINDOWS STUFF
#ifdef _WIN32
#include <windows.h>

// UNIX STUFF
#else
#include <pthread.h>
#endif

#include <stdio.h>
#include "except.h"

... 

then in the include put the magic word in "__thread": 

extern __thread Except_Frame *Except_stack;
extern __thread const Except_T Assert_Failed;

also in the C file:

__thread Except_Frame *Except_stack = NULL;


now Except_stack is thread local

Note for MingW: compile with -mthreads (or test it yourself)

For Visual Studio (no mean comment :P)

extern __declspec( thread ) Except_Frame *Except_stack;
extern __declspec( thread ) const Except_T Assert_Failed;

also in the C file:

__declspec( thread ) Except_Frame *Except_stack = NULL;

in case you have problems with VS see:
http://msdn.microsoft.com/en-us/library/dabb5z75.aspx


Also useful info can be found here: 
http://en.wikipedia.org/wiki/Thread-local_storage

Regards,
Alex 

Original comment by ealexs on 21 Feb 2011 at 2:55