Skip to content

Commit

Permalink
Add a test to show how unique_ptr may be used
Browse files Browse the repository at this point in the history
  • Loading branch information
hirak99 committed Aug 30, 2020
1 parent 5e1a082 commit 51fd57e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
4 changes: 2 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror")

set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")
set (CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")
set(CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")

# Locate GTest
find_package(GTest REQUIRED)
Expand Down
9 changes: 7 additions & 2 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ cd build
# g++ -std=c++17 -g ../demo.cpp -lpthread -o ./demo
# ./demo

cmake -DCMAKE_BUILD_TYPE=Debug .. -GNinja
ninja
cmake -DCMAKE_BUILD_TYPE=Debug ..
make

# Replace with lines below for building with Ninja.
# cmake -DCMAKE_BUILD_TYPE=Debug .. -GNinja
# ninja

GTEST_COLOR=1 ctest -V
21 changes: 19 additions & 2 deletions thread_pool_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#include <gtest/gtest.h>

#include <memory>

TEST(ThreadPoolTest, Threaded) {
std::vector<int> visit_count(50, 0);
{
Expand All @@ -10,8 +12,23 @@ TEST(ThreadPoolTest, Threaded) {
thread_pool.Do([&visit_count, i] { ++visit_count[i]; });
}
}
ASSERT_TRUE(std::all_of(visit_count.begin(), visit_count.end(),
[](int value) { return value == 1; }));
ASSERT_EQ(visit_count, std::vector<int>(50, 1));
}

// Demonstrates passing parameters via unique_ptr.
TEST(ThreadPoolTest, UniquePtr) {
std::vector<int> visit_count(50, 0);
{
ThreadPool thread_pool{10, 5};
for (int i = 0; i < 50; ++i) {
auto uptr = std::make_unique<int>(i);
// Move to a shared ptr to make it copyable, and hand over to the thread
// pool.
std::shared_ptr<int> sptr = std::move(uptr);
thread_pool.Do([&visit_count, sptr] { ++visit_count[*sptr]; });
}
}
ASSERT_EQ(visit_count, std::vector<int>(50, 1));
}

int main(int argc, char** argv) {
Expand Down

0 comments on commit 51fd57e

Please sign in to comment.