Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{7f150933-516e-4c74-89b3-73754086ff32}</ProjectGuid>
<ProjectGuid>{7F150933-516E-4C74-89B3-73754086FF32}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<WindowsTargetPlatformVersion>10.0.26100.0</WindowsTargetPlatformVersion>
<ConfigurationType>Application</ConfigurationType>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{5f6662cb-9d21-4ce5-8716-77bdad8212a8}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<WindowsTargetPlatformVersion>10.0.26100.0</WindowsTargetPlatformVersion>
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v145</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings" />
<ImportGroup Label="Shared" />
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>X64;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PreprocessorDefinitions>X64;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="test.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.1.8.1.8\build\native\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.targets" Condition="Exists('..\..\packages\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.1.8.1.8\build\native\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.1.8.1.8\build\native\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.1.8.1.8\build\native\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.targets'))" />
</Target>
</Project>
4 changes: 4 additions & 0 deletions Tests/SharedPtrWaitingThreadSafeStack.Tests/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn" version="1.8.1.8" targetFramework="native" />
</packages>
5 changes: 5 additions & 0 deletions Tests/SharedPtrWaitingThreadSafeStack.Tests/pch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
//
// pch.cpp
//

#include "pch.h"
7 changes: 7 additions & 0 deletions Tests/SharedPtrWaitingThreadSafeStack.Tests/pch.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//
// pch.h
//

#pragma once

#include "gtest/gtest.h"
167 changes: 167 additions & 0 deletions Tests/SharedPtrWaitingThreadSafeStack.Tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
#include "pch.h"
#include <gtest/gtest.h>
#include <thread>
#include <chrono>
#include <vector>
#include <memory>

#include "../../ThreadSafeStack/SharedPtrWaitingThreadSafeStack.h"

using namespace std::chrono_literals;

/**
* @category Functional Tests
* @brief Basic validation of the stack's LIFO logic and state management.
*/

// @test Validates that the stack is correctly initialized without any elements.
TEST(SharedPtrWaitingThreadSafeStackTest, ConstructorInitializesEmpty) {
SharedPtrWaitingThreadSafeStack<int> stack;
EXPECT_TRUE(stack.isEmpty());
EXPECT_EQ(stack.getSize(), 0);
}

// @test Verifies that pushing elements increases size and preserves LIFO order.
TEST(SharedPtrWaitingThreadSafeStackTest, PushAndTryPopValueIntegrity) {
SharedPtrWaitingThreadSafeStack<std::string> stack;
stack.push("Alpha");
stack.push("Beta");

EXPECT_EQ(stack.getSize(), 2);

std::string out;
EXPECT_TRUE(stack.tryPop(out));
EXPECT_EQ(out, "Beta");

auto ptr = stack.tryPop();
ASSERT_NE(ptr, nullptr);
EXPECT_EQ(*ptr, "Alpha");
}

// @test Ensures that clear() effectively removes all elements and resets size.
TEST(SharedPtrWaitingThreadSafeStackTest, ClearResetsStackState) {
SharedPtrWaitingThreadSafeStack<int> stack;
for (int i = 0; i < 100; ++i) stack.push(i);

EXPECT_EQ(stack.getSize(), 100);
stack.clear();
EXPECT_TRUE(stack.isEmpty());
EXPECT_EQ(stack.getSize(), 0);
}

/**
* @category Concurrency & Synchronization
* @brief Tests the blocking behavior and thread-safety of the implementation.
*/

// @test Validates the producer-consumer pattern using blocking waitAndPop.
TEST(SharedPtrWaitingThreadSafeStackTest, WaitAndPopBlocksUntilDataIsPushed) {
SharedPtrWaitingThreadSafeStack<int> stack;
int poppedValue = 0;
std::atomic<bool> threadFinished{ false };

std::thread consumer([&]() {
stack.waitAndPop(poppedValue);
threadFinished = true;
});

// Brief delay to ensure consumer is in waiting state
std::this_thread::sleep_for(50ms);
EXPECT_FALSE(threadFinished);

stack.push(123);
consumer.join();

EXPECT_TRUE(threadFinished);
EXPECT_EQ(poppedValue, 123);
}

/**
* @test Verifies that waitAndPopFor accurately respects the timeout
* when the stack remains empty.
*/
TEST(SharedPtrWaitingThreadSafeStackTest, WaitAndPopForRespectsTimeout) {
SharedPtrWaitingThreadSafeStack<int> stack;
int value = 0;

auto start = std::chrono::steady_clock::now();
bool result = stack.waitAndPopFor(value, 150ms);
auto end = std::chrono::steady_clock::now();

EXPECT_FALSE(result);
EXPECT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(), 140);
}

/**
* @category Memory & Resource Management
* @brief Checks for proper handling of shared_ptr and move semantics.
*/

// @test Ensures that the stack correctly moves non-copyable or large objects.
TEST(SharedPtrWaitingThreadSafeStackTest, HandlesMoveOnlyObjects) {
// Using unique_ptr inside shared_ptr logic is a good test for move-heavy paths
SharedPtrWaitingThreadSafeStack<std::unique_ptr<int>> stack;

auto item = std::make_unique<int>(1000);
stack.push(std::move(item));

auto poppedPtr = stack.waitAndPop();
ASSERT_NE(poppedPtr, nullptr);
ASSERT_NE(*poppedPtr, nullptr);
EXPECT_EQ(**poppedPtr, 1000);
}

// @test Verifies that the copy constructor performs a thread-safe deep copy.
TEST(SharedPtrWaitingThreadSafeStackTest, CopyConstructorThreadSafety) {
SharedPtrWaitingThreadSafeStack<int> original;
original.push(1);
original.push(2);

SharedPtrWaitingThreadSafeStack<int> copy(original);

EXPECT_EQ(copy.getSize(), 2);
EXPECT_EQ(*copy.tryPop(), 2);
// Original should remain intact
EXPECT_EQ(original.getSize(), 2);
}

/**
* @category Stress Test
* @brief High-contention test to ensure data integrity under heavy load.
*/
TEST(SharedPtrWaitingThreadSafeStackTest, HighContentionStressTest) {
SharedPtrWaitingThreadSafeStack<long long> stack;
const int producersCount = 10;
const int consumersCount = 10;
const int itemsPerProducer = 1000;

std::atomic<long long> totalSumPopped{ 0 };
std::vector<std::thread> threads;

// Launch producers
for (int i = 0; i < producersCount; ++i) {
threads.emplace_back([&stack, itemsPerProducer]() {
for (int j = 1; j <= itemsPerProducer; ++j) {
stack.push(j);
}
});
}

// Launch consumers
for (int i = 0; i < consumersCount; ++i) {
threads.emplace_back([&stack, &totalSumPopped, itemsPerProducer]() {
for (int j = 0; j < itemsPerProducer; ++j) {
totalSumPopped += *stack.waitAndPop();
}
});
}

for (auto& t : threads) t.join();

// Verification via arithmetic progression sum: n * (n + 1) / 2
long long expectedSumPerProducer = (1LL * itemsPerProducer * (itemsPerProducer + 1)) / 2;
long long totalExpectedSum = expectedSumPerProducer * producersCount;

EXPECT_EQ(totalSumPopped.load(), totalExpectedSum);
EXPECT_TRUE(stack.isEmpty());
}
1 change: 1 addition & 0 deletions ThreadSafeStack.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<Platform Name="x86" />
</Configurations>
<Project Path="Tests/ModernThreadSafeStack.Tests/ModernThreadSafeStack.Tests.vcxproj" Id="7f150933-516e-4c74-89b3-73754086ff32" />
<Project Path="Tests/SharedPtrWaitingThreadSafeStack.Tests/SharedPtrWaitingThreadSafeStack.Tests.vcxproj" Id="5f6662cb-9d21-4ce5-8716-77bdad8212a8" />
<Project Path="Tests/WaitingThreadSafeStack.Tests/WaitingThreadSafeStack.Tests.vcxproj" Id="763327fa-3786-480d-8bf6-856899243cd6" />
<Project Path="ThreadSafeStack/ThreadSafeStack.vcxproj" Id="fcf27f67-3832-4d60-a114-fd618ddb9116" />
</Solution>
11 changes: 11 additions & 0 deletions ThreadSafeStack/SharedPtrWaitingThreadSafeStack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#include "SharedPtrWaitingThreadSafeStack.h"

// Explicit template instantiations for commonly used types.
// This forces the compiler to generate implementations for these types
// in this translation unit. This approach helps reduce compilation times
// and avoids potential linker issues when the template is used across
// multiple translation units.

template class SharedPtrWaitingThreadSafeStack<int>;
template class SharedPtrWaitingThreadSafeStack<double>;
template class SharedPtrWaitingThreadSafeStack<std::string>;
Loading