70 lines · cpp
1//===-- thread_contention.cpp -----------------------------------*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "gwp_asan/tests/harness.h"10 11// Note: Compilation of <atomic> and <thread> are extremely expensive for12// non-opt builds of clang.13#include <atomic>14#include <cstdlib>15#include <thread>16#include <vector>17 18namespace {19 20void asyncTask(gwp_asan::GuardedPoolAllocator *GPA,21 std::atomic<bool> *StartingGun, unsigned NumIterations) {22 while (!*StartingGun) {23 // Wait for starting gun.24 }25 26 // Get ourselves a new allocation.27 for (unsigned i = 0; i < NumIterations; ++i) {28 volatile char *Ptr = reinterpret_cast<volatile char *>(29 GPA->allocate(GPA->getAllocatorState()->maximumAllocationSize()));30 // Do any other threads have access to this page?31 EXPECT_EQ(*Ptr, 0);32 33 // Mark the page as from malloc. Wait to see if another thread also takes34 // this page.35 *Ptr = 'A';36 std::this_thread::sleep_for(std::chrono::nanoseconds(10000));37 38 // Check we still own the page.39 EXPECT_EQ(*Ptr, 'A');40 41 // And now release it.42 *Ptr = 0;43 GPA->deallocate(const_cast<char *>(Ptr));44 }45}46 47void runThreadContentionTest(unsigned NumThreads, unsigned NumIterations,48 gwp_asan::GuardedPoolAllocator *GPA) {49 std::atomic<bool> StartingGun{false};50 std::vector<std::thread> Threads;51 52 for (unsigned i = 0; i < NumThreads; ++i) {53 Threads.emplace_back(asyncTask, GPA, &StartingGun, NumIterations);54 }55 56 StartingGun = true;57 58 for (auto &T : Threads)59 T.join();60}61 62TEST_F(CustomGuardedPoolAllocator, ThreadContention) {63 unsigned NumThreads = 4;64 unsigned NumIterations = 10000;65 InitNumSlots(NumThreads);66 runThreadContentionTest(NumThreads, NumIterations, &GPA);67}68 69} // namespace70