0

I am trying to write some library code that may be used by people who have pthreads enabled (or not), and by people who have openmp support (or not). I have some variable that I really want to be in thread-local storage. Is there any potential harm in specifying this twice, for example

#ifdef __GNUC__
# define PREFIX __thread
#elif __STDC_VERSION__ >= 201112L
# define PREFIX _Thread_local
#elif defined(_MSC_VER)
# define PREFIX __declspec(thread)
#else
# define PREFIX
#endif

PREFIX int var = 10;
#pragma omp threadprivate(var)

(Note, the business to figure out the TLS prefix is taken from How to declare a variable as thread local portably?)

I know this works on my system (Debian with recent gcc) but it's hard to know whether things could go wrong elsewhere since these compiler-specific declarations are not part of the OpenMP standard.

Community
  • 1
  • 1
Dan R
  • 1,412
  • 11
  • 21
  • Why don't you first check for the C standard, then for compiler extensions? – too honest for this site Jun 26 '16 at 04:03
  • @Olaf I was just matching the way it was suggested in the other SO question I linked. Anyway I don't think it matters at all for the purposes of the question I'm asking here. – Dan R Jun 26 '16 at 04:11
  • Well, don't follow a pattern if you don't know what it does. It is generally bad design to use extensions if a feature is provided by the standard. Always use the most general way first. – too honest for this site Jun 26 '16 at 04:19

1 Answers1

1

What about:

#if __STDC_VERSION__ >= 201112L
# define PREFIX _Thread_local
#elif defined(__GNUC__)
# define PREFIX __thread
#elif defined(_MSC_VER)
# define PREFIX __declspec(thread)
#else
# define PREFIX
#endif

PREFIX int var = 10;
#if !PREFIX
#ifdef _OPENMP
#pragma omp threadprivate(var)
#else
#error "Failure to put variable into TLS"
#endif
#endif

GCC doesn't mind the over-specifying because __thread is an implicit #pragma omp threadprivate anyway.

Instead of worrying about compilers where this might not be the case, just use OpenMP's threadprivate conditionally.

a3f
  • 8,517
  • 1
  • 41
  • 46
  • Last time I checked `musl` did not work with `gomp`. so if the OP used a standard library other than `glibc` OpenMP might not be available. – Z boson Jun 26 '16 at 08:19
  • Thanks, but I was asking more about whether there's anything wrong with double-specifying, rather than a way to avoid it with more preprocessor directives. – Dan R Jun 26 '16 at 11:48
  • @DanRoche I am afraid there is no definite answer for that. It's not specified anywhere what should happen in such a case. Best is to avoid it. – a3f Jun 26 '16 at 20:52