HeapAlloc() function and 3 threads

  • Thread starter Thread starter Zuhlik
  • Start date Start date
Z

Zuhlik

Guest
I would like to expand the WinAPI console application that draws random numbers and calculates the average, maximum and minimum in one thread to three separate threads for each function.
I use below tutorial, among others, and I wonder if it is necessary to allocate a block of memory from a heap using the HeapAlloc() and HeapFree() functions? I can not find anything satisfactory on this topic in the provided materials.
Could someone explain in simple words if and why such allocation is required?
How such allocation should be properly done for 3 threads using HeapAlloc()?
In the next step i would like to test critical section for thread synchronization.
A slightly modified sample code using semaphores below.

C++ Tutorial: Multi-Threaded Programming II - Thread for Win32 (B) - 2018

#include <Windows.h>
#include <process.h>
#include <iostream>

using namespace std;

HANDLE semaphore;
int count1 = 0;
int count2 = 0;
int count3 = 0;

void addCount(int increment)
{
WaitForSingleObject(semaphore, INFINITE);
count1 += increment;
ReleaseSemaphore(semaphore, 1, 0);
}

void subCount(int decrement)
{
WaitForSingleObject(semaphore, INFINITE);
count2 -= decrement;
ReleaseSemaphore(semaphore, 1, 0);
}

void mulCount(int multiply)
{
WaitForSingleObject(semaphore, INFINITE);
count3 *= multiply;
ReleaseSemaphore(semaphore, 1, 0);
}

unsigned int __stdcall mythread1(void*)
{
addCount(12);
return 0;
}

unsigned int __stdcall mythread2(void*)
{
subCount(56);
return 0;
}

unsigned int __stdcall mythread3(void*)
{
mulCount(22);
return 0;
}

int main(int argc, char* argv[])
{
HANDLE myhandleA, myhandleB, myhandleC;

semaphore = CreateSemaphore(0, 1, 1, 0);

myhandleA = (HANDLE)_beginthreadex(0, 0, &mythread1, (void*)0, 0, 0);
myhandleB = (HANDLE)_beginthreadex(0, 0, &mythread2, (void*)0, 0, 0);
myhandleC = (HANDLE)_beginthreadex(0, 0, &mythread3, (void*)0, 0, 0);

WaitForSingleObject(myhandleA, INFINITE);
WaitForSingleObject(myhandleB, INFINITE);
WaitForSingleObject(myhandleC, INFINITE);

CloseHandle(myhandleA);
CloseHandle(myhandleB);
CloseHandle(myhandleC);

cout << "Count1 = " << count1 << endl;
cout << "Count2 = " << count2 << endl;
cout << "Count3 = " << count3 << endl;

CloseHandle(semaphore);

return 0;
}

Continue reading...
 
Back
Top