thread_local_unittests.cc 2.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <thread>

#include "flutter/fml/thread_local.h"
#include "gtest/gtest.h"

// We are only going to test the pthreads based thread local boxes.
#if FML_THREAD_LOCAL_PTHREADS

TEST(ThreadLocal, SimpleInitialization) {
  std::thread thread([&] {
    fml::ThreadLocal local;
    auto value = 100;
    local.Set(value);
    ASSERT_EQ(local.Get(), value);
  });
  thread.join();
}

TEST(ThreadLocal, SimpleInitializationCheckInAnother) {
  std::thread thread([&] {
    fml::ThreadLocal local;
    auto value = 100;
    local.Set(value);
    ASSERT_EQ(local.Get(), value);
    std::thread thread2([&]() { ASSERT_EQ(local.Get(), 0); });
    thread2.join();
  });
  thread.join();
}

TEST(ThreadLocal, DestroyCallback) {
  std::thread thread([&] {
    int destroys = 0;
    fml::ThreadLocal local([&destroys](intptr_t) { destroys++; });
    auto value = 100;
    local.Set(value);
    ASSERT_EQ(local.Get(), value);
    ASSERT_EQ(destroys, 0);
  });
  thread.join();
}

TEST(ThreadLocal, DestroyCallback2) {
  std::thread thread([&] {
    int destroys = 0;
    fml::ThreadLocal local([&destroys](intptr_t) { destroys++; });

    local.Set(100);
    ASSERT_EQ(local.Get(), 100);
    ASSERT_EQ(destroys, 0);
    local.Set(200);
    ASSERT_EQ(local.Get(), 200);
    ASSERT_EQ(destroys, 1);
  });
  thread.join();
}

TEST(ThreadLocal, DestroyThreadTimeline) {
  std::thread thread([&] {
    int destroys = 0;
    fml::ThreadLocal local([&destroys](intptr_t) { destroys++; });

    std::thread thread([&]() {
      local.Set(100);
      ASSERT_EQ(local.Get(), 100);
      ASSERT_EQ(destroys, 0);
      local.Set(200);
      ASSERT_EQ(local.Get(), 200);
      ASSERT_EQ(destroys, 1);
    });
    ASSERT_EQ(local.Get(), 0);
    thread.join();
    ASSERT_EQ(local.Get(), 0);
    ASSERT_EQ(destroys, 2);
  });
  thread.join();
}

TEST(ThreadLocal, SettingSameValue) {
  std::thread thread([&] {
    int destroys = 0;
    {
      fml::ThreadLocal local([&destroys](intptr_t) { destroys++; });

      local.Set(100);
      ASSERT_EQ(destroys, 0);
      local.Set(100);
      local.Set(100);
      local.Set(100);
      ASSERT_EQ(local.Get(), 100);
      local.Set(100);
      local.Set(100);
      ASSERT_EQ(destroys, 0);
      local.Set(200);
      ASSERT_EQ(destroys, 1);
      ASSERT_EQ(local.Get(), 200);
    }

    ASSERT_EQ(destroys, 1);
  });
  thread.join();
}

#endif  // FML_THREAD_LOCAL_PTHREADS