forked from huntercbx/parallel-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
31 changed files
with
3,833 additions
and
0 deletions.
There are no files selected for viewing
154 changes: 154 additions & 0 deletions
154
03 - WinAPI Threads Examples/01 - Create Threads/01 - Create Threads.vcxproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<Project DefaultTargets="Build" ToolsVersion="14.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>{058A4FBF-5E18-4BE5-A24C-0489107D5D41}</ProjectGuid> | ||
<Keyword>Win32Proj</Keyword> | ||
<RootNamespace>My01CreateThreads</RootNamespace> | ||
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion> | ||
</PropertyGroup> | ||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> | ||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> | ||
<ConfigurationType>Application</ConfigurationType> | ||
<UseDebugLibraries>true</UseDebugLibraries> | ||
<PlatformToolset>v140</PlatformToolset> | ||
<CharacterSet>Unicode</CharacterSet> | ||
</PropertyGroup> | ||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> | ||
<ConfigurationType>Application</ConfigurationType> | ||
<UseDebugLibraries>false</UseDebugLibraries> | ||
<PlatformToolset>v140</PlatformToolset> | ||
<WholeProgramOptimization>true</WholeProgramOptimization> | ||
<CharacterSet>Unicode</CharacterSet> | ||
</PropertyGroup> | ||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> | ||
<ConfigurationType>Application</ConfigurationType> | ||
<UseDebugLibraries>true</UseDebugLibraries> | ||
<PlatformToolset>v140</PlatformToolset> | ||
<CharacterSet>Unicode</CharacterSet> | ||
</PropertyGroup> | ||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> | ||
<ConfigurationType>Application</ConfigurationType> | ||
<UseDebugLibraries>false</UseDebugLibraries> | ||
<PlatformToolset>v140</PlatformToolset> | ||
<WholeProgramOptimization>true</WholeProgramOptimization> | ||
<CharacterSet>Unicode</CharacterSet> | ||
</PropertyGroup> | ||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> | ||
<ImportGroup Label="ExtensionSettings"> | ||
</ImportGroup> | ||
<ImportGroup Label="Shared"> | ||
</ImportGroup> | ||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> | ||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> | ||
</ImportGroup> | ||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> | ||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> | ||
</ImportGroup> | ||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> | ||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> | ||
</ImportGroup> | ||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> | ||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> | ||
</ImportGroup> | ||
<PropertyGroup Label="UserMacros" /> | ||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> | ||
<LinkIncremental>true</LinkIncremental> | ||
<TargetName>CreateThreads</TargetName> | ||
</PropertyGroup> | ||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> | ||
<LinkIncremental>true</LinkIncremental> | ||
<TargetName>CreateThreads</TargetName> | ||
</PropertyGroup> | ||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> | ||
<LinkIncremental>false</LinkIncremental> | ||
<TargetName>CreateThreads</TargetName> | ||
</PropertyGroup> | ||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> | ||
<LinkIncremental>false</LinkIncremental> | ||
<TargetName>CreateThreads</TargetName> | ||
</PropertyGroup> | ||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> | ||
<ClCompile> | ||
<PrecompiledHeader> | ||
</PrecompiledHeader> | ||
<WarningLevel>Level3</WarningLevel> | ||
<Optimization>Disabled</Optimization> | ||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> | ||
</ClCompile> | ||
<Link> | ||
<SubSystem>Console</SubSystem> | ||
<GenerateDebugInformation>true</GenerateDebugInformation> | ||
</Link> | ||
</ItemDefinitionGroup> | ||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> | ||
<ClCompile> | ||
<PrecompiledHeader> | ||
</PrecompiledHeader> | ||
<WarningLevel>Level3</WarningLevel> | ||
<Optimization>Disabled</Optimization> | ||
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> | ||
</ClCompile> | ||
<Link> | ||
<SubSystem>Console</SubSystem> | ||
<GenerateDebugInformation>true</GenerateDebugInformation> | ||
</Link> | ||
</ItemDefinitionGroup> | ||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> | ||
<ClCompile> | ||
<WarningLevel>Level3</WarningLevel> | ||
<PrecompiledHeader> | ||
</PrecompiledHeader> | ||
<Optimization>MaxSpeed</Optimization> | ||
<FunctionLevelLinking>true</FunctionLevelLinking> | ||
<IntrinsicFunctions>true</IntrinsicFunctions> | ||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> | ||
</ClCompile> | ||
<Link> | ||
<SubSystem>Console</SubSystem> | ||
<GenerateDebugInformation>true</GenerateDebugInformation> | ||
<EnableCOMDATFolding>true</EnableCOMDATFolding> | ||
<OptimizeReferences>true</OptimizeReferences> | ||
</Link> | ||
</ItemDefinitionGroup> | ||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> | ||
<ClCompile> | ||
<WarningLevel>Level3</WarningLevel> | ||
<PrecompiledHeader> | ||
</PrecompiledHeader> | ||
<Optimization>MaxSpeed</Optimization> | ||
<FunctionLevelLinking>true</FunctionLevelLinking> | ||
<IntrinsicFunctions>true</IntrinsicFunctions> | ||
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> | ||
</ClCompile> | ||
<Link> | ||
<SubSystem>Console</SubSystem> | ||
<GenerateDebugInformation>true</GenerateDebugInformation> | ||
<EnableCOMDATFolding>true</EnableCOMDATFolding> | ||
<OptimizeReferences>true</OptimizeReferences> | ||
</Link> | ||
</ItemDefinitionGroup> | ||
<ItemGroup> | ||
<ClCompile Include="CreateThreads.cpp" /> | ||
</ItemGroup> | ||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> | ||
<ImportGroup Label="ExtensionTargets"> | ||
</ImportGroup> | ||
</Project> |
6 changes: 6 additions & 0 deletions
6
03 - WinAPI Threads Examples/01 - Create Threads/01 - Create Threads.vcxproj.filters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> | ||
<ItemGroup> | ||
<ClCompile Include="CreateThreads.cpp" /> | ||
</ItemGroup> | ||
</Project> |
96 changes: 96 additions & 0 deletions
96
03 - WinAPI Threads Examples/01 - Create Threads/CreateThreads.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
//////////////////////////////////////////////////////////////////////////////// | ||
/// Демонстрация создания многопочного приложения | ||
/// | ||
/// Создается несколько потоков, помимо основного. Для каждого потока выводится | ||
/// его идентификатор и идентификатор процесса, которому поток принадлежит. | ||
/// Идентификаторы потоков должны быть разные, а процесса - одинаковый. | ||
/// | ||
/// В данном примере демонстрируется передача данных в поток, для чего | ||
/// используется структура MyStruct. | ||
/// Каждому потоку передается свой экземпляр структуры. | ||
/// | ||
/// Следует обратить внимание: | ||
/// - что основной поток продолжает работу после создания остальных потоков; | ||
/// - на использование функции WaitForMultipleObjects для ожидания завершения | ||
/// всех потоков. | ||
//////////////////////////////////////////////////////////////////////////////// | ||
|
||
#include <windows.h> | ||
#include <stdio.h> | ||
|
||
// Количество создаваемых потоков | ||
const int N_THREADS = 8; | ||
|
||
// Пример структуры данных, передаваемой в поток | ||
struct MyStruct | ||
{ | ||
int val1; | ||
int val2; | ||
}; | ||
|
||
// Функция потока | ||
DWORD WINAPI MyThreadFunction(LPVOID lpParam) | ||
{ | ||
// Приведение указателя на данные к нужному типу | ||
MyStruct* pMyStruct = reinterpret_cast<MyStruct*>(lpParam); | ||
|
||
// Вывод идентификаторов текущего процесса, потока и параметров | ||
printf_s( | ||
"Process ID = %d, Thread ID = %d, Parameters = %d, %d\n", | ||
GetCurrentProcessId(), | ||
GetCurrentThreadId(), | ||
pMyStruct->val1, | ||
pMyStruct->val2); | ||
return 0; | ||
} | ||
|
||
int main(int argc, char* argv[]) | ||
{ | ||
// Вывод идентификаторов текущего процесса и потока | ||
printf_s("Process ID = %d, Thread ID = %d, This is main thread\n", | ||
GetCurrentProcessId(), | ||
GetCurrentThreadId()); | ||
|
||
MyStruct data[N_THREADS]; // данные для работы потоков | ||
DWORD dwThreadIdArray[N_THREADS]; // идентификаторы потоков | ||
HANDLE hThreadArray[N_THREADS]; // дескрипторы потоков | ||
|
||
// Создание требуемого (N_THREADS) числа потоков | ||
for (int i = 0; i < N_THREADS; ++i) | ||
{ | ||
// Заполнение полей структуры, передаваемой в поток | ||
data[i].val1 = i; | ||
data[i].val2 = i * 101; | ||
|
||
// Создание нового потока | ||
hThreadArray[i] = CreateThread( | ||
NULL, // использовать настройки безопасности по умолчанию | ||
0, // использовать размер стека по умолчанию | ||
MyThreadFunction, // имя функции потока | ||
&data[i], // аргумент для потока | ||
0, // создать поток с флагами по умолчанию | ||
&dwThreadIdArray[i]); // идентификатор потока | ||
|
||
// Если поток не был создан - завершаем работу с ошибкой | ||
if (hThreadArray[i] == NULL) | ||
ExitProcess(1); | ||
} | ||
|
||
// Основной поток продолжает работу | ||
printf_s("Process ID = %d, Thread ID = %d, Main thread is still running!\n", | ||
GetCurrentProcessId(), | ||
GetCurrentThreadId()); | ||
|
||
// Ожидаем завершения всех потоков | ||
WaitForMultipleObjects( | ||
N_THREADS, // количество потоков | ||
hThreadArray, // дескрипторы потоков | ||
TRUE, // ждем завершения всех потоков | ||
INFINITE); // ждем в течении бесконечного времени | ||
|
||
// Освобождаем дескрипторы потоков | ||
for (int i = 0; i < N_THREADS; ++i) | ||
CloseHandle(hThreadArray[i]); | ||
|
||
return 0; | ||
} |
Oops, something went wrong.