Skip to content

Commit

Permalink
fix when running under tsan
Browse files Browse the repository at this point in the history
  • Loading branch information
dconeybe committed Jan 14, 2025
1 parent fae4442 commit 8f5d1e9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Firestore/core/test/unit/util/thread_safe_memoizer_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ TEST(ThreadSafeMemoizerTest,

TEST(ThreadSafeMemoizerTest, TSAN_ConcurrentCallsToValueShouldNotDataRace) {
ThreadSafeMemoizer<int> memoizer;
const auto num_threads = max_practical_parallel_threads_for_testing() * 4;
const auto num_threads = max_practical_parallel_threads_for_testing();
CountDownLatch latch(num_threads);
std::vector<std::thread> threads;
for (auto i = num_threads; i > 0; --i) {
Expand Down
23 changes: 21 additions & 2 deletions Firestore/core/test/unit/util/thread_safe_memoizer_testing.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#include "Firestore/core/test/unit/util/thread_safe_memoizer_testing.h"

#include <algorithm>
#include <cassert>
#include <functional>
#include <memory>
Expand All @@ -26,11 +27,20 @@
#include <utility>
#include <vector>

#include "Firestore/core/src/util/sanitizers.h"

namespace firebase {
namespace firestore {
namespace testing {
namespace {

constexpr bool kIsRunningUnderThreadSanitizer =
#if THREAD_SANITIZER
true;
#else
false;
#endif

std::vector<std::string> SplitSeparators(const std::string& s) {
std::vector<std::string> chunks;

Expand Down Expand Up @@ -103,14 +113,23 @@ CountDownLatch::CountDownLatch(int count) {
void CountDownLatch::arrive_and_wait() {
count_.fetch_sub(1, std::memory_order_acq_rel);
while (count_.load(std::memory_order_acquire) > 0) {
// do nothing; busy wait.
std::this_thread::yield();
}
}

decltype(std::thread::hardware_concurrency())
max_practical_parallel_threads_for_testing() {
const auto hardware_concurrency = std::thread::hardware_concurrency();
return hardware_concurrency != 0 ? hardware_concurrency : 4;
const auto num_threads = hardware_concurrency != 0 ? hardware_concurrency : 4;

// Limit the number of threads when running under Thread Sanitizer as the
// boilerplate that it puts around atomics is so much that a large number of
// threads competing for a std::atomic can bring the app to its knees.
if (kIsRunningUnderThreadSanitizer) {
return std::min(static_cast<int>(num_threads), 10);
}

return num_threads;
}

bool GenerateRandomBool() {
Expand Down

0 comments on commit 8f5d1e9

Please sign in to comment.