
AC_DEFUN([VG_CHECK_TLS],[
ac_save_CFLAGS=$CFLAGS
CFLAGS="-lpthread"
# Check for TLS support in the compiler and linker
AC_CACHE_CHECK([for TLS support], vg_cv_tls,
	       [AC_ARG_ENABLE(tls, [  --enable-tls            platform supports TLS],
		[vg_cv_tls=$enableval],
               	[AC_RUN_IFELSE([AC_LANG_PROGRAM(

[[
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>

#define COUNT 10

static __thread int local;

/* Count need not be complete ... */
volatile static int errors_found = 0;

static const struct timespec awhile = { 0, 100000000 };

static void *tls_ptr(void *p)
{
  int *ip = (int*)p;
  int here = 0;
  int i;
  
  for(i = 0; i < COUNT; i++) {
    int a = (*ip)++;
    int b = here++;
    if (a != b || errors_found != 0) {
      errors_found++;	  
      return 0;
    }
    nanosleep(&awhile, 0);
  }
  
  return 0;
}

]],
[[
#define NTESTERS 2

pthread_t threads[NTESTERS];
int curthread = 0;
static int i;

for(i = 0; i < NTESTERS; i++) {
  pthread_create(&threads[curthread++], NULL, tls_ptr, (void *)&local);
}

for(i = 0; i < curthread; i++)
  pthread_join(threads[i], NULL);

return errors_found;
]])],
                               [vg_cv_tls=yes],
                               [vg_cv_tls=no])])])

CFLAGS=$ac_save_CFLAGS

if test "$vg_cv_tls" = yes; then
AC_DEFINE([HAVE_TLS], 1, [can use __thread to define thread-local variables])
fi
])