ManagedStatic.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //===- llvm/unittest/Support/ManagedStatic.cpp - ManagedStatic tests ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/Support/ManagedStatic.h"
  10. #include "llvm/Config/config.h"
  11. #include "llvm/Support/Threading.h"
  12. #ifdef HAVE_PTHREAD_H
  13. #include <pthread.h>
  14. #endif
  15. // //
  16. ///////////////////////////////////////////////////////////////////////////////
  17. #include "gtest/gtest.h"
  18. using namespace llvm;
  19. namespace {
  20. #if LLVM_ENABLE_THREADS != 0 && defined(HAVE_PTHREAD_H) && \
  21. !__has_feature(memory_sanitizer)
  22. namespace test1 {
  23. llvm::ManagedStatic<int> ms;
  24. void *helper(void*) {
  25. *ms;
  26. return nullptr;
  27. }
  28. // Valgrind's leak checker complains glibc's stack allocation.
  29. // To appease valgrind, we provide our own stack for each thread.
  30. void *allocate_stack(pthread_attr_t &a, size_t n = 65536) {
  31. void *stack = malloc(n);
  32. pthread_attr_init(&a);
  33. #if defined(__linux__)
  34. pthread_attr_setstack(&a, stack, n);
  35. #endif
  36. return stack;
  37. }
  38. }
  39. TEST(Initialize, MultipleThreads) {
  40. // Run this test under tsan: http://code.google.com/p/data-race-test/
  41. pthread_attr_t a1, a2;
  42. void *p1 = test1::allocate_stack(a1);
  43. void *p2 = test1::allocate_stack(a2);
  44. pthread_t t1, t2;
  45. pthread_create(&t1, &a1, test1::helper, nullptr);
  46. pthread_create(&t2, &a2, test1::helper, nullptr);
  47. pthread_join(t1, nullptr);
  48. pthread_join(t2, nullptr);
  49. free(p1);
  50. free(p2);
  51. }
  52. #endif
  53. } // anonymous namespace