+7(960) 250-82-68 spam@mirossa.ru


  MCU         C           1С         PHP       JAVA      разное 


Статьи
 
 

Потоки и мьютексы

//компиляция C-Free
//cd "C:\Program Files (x86)\C-Free 5\mingw\bin"
//gcc.exe beer.c -o beer.exe


#include <stdio.h>
#include <windows.h>

void error(char * msg)
{
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(1);
}

int beers = 2000000;

//функция потока
DWORD WINAPI drink_lots( LPVOID lpParam )
{
CONST HANDLE hMutex = (CONST HANDLE)lpParam;

int i;
WaitForSingleObject(hMutex, INFINITE); //ждём освобождение мьютекса и ставим блокировку
for (i = 0; i < 100000; i++){
beers = beers - 1;

}
ReleaseMutex(hMutex);
printf("beers = %i\n", beers);

ExitThread(0);
}


int main(){

SetConsoleCP(1251); // На ввод
SetConsoleOutputCP(1251); //На вывод.

HANDLE hThreadArray[20];
DWORD dwThreadIdArray[20];

CONST HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
if(NULL == hMutex) {
error("Failed to create mutex.\r\n");
}

int t;
printf(" %i бутылок пива на стене, %i бутылок пива\n", beers, beers);
for (t = 0; t < 20; t++) {


//A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and 
//_endthreadex functions. for thread management rather than CreateThread and ExitThread; this 
//requires the use of the multithreaded version of the CRT. If a thread created using CreateThread 
//calls the CRT, the CRT may terminate the process in low-memory conditions.
// https://docs.microsoft.com/ru-ru/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createthread


hThreadArray[t] = CreateThread(
NULL, // default security attributes
0, // use default stack siz
drink_lots, // thread function name
hMutex, // argument to thread function
0, // use default creation flags
&dwThreadIdArray[t]); // returns the thread identifier

// Check the return value for success.
// If CreateThread fails, terminate execution.
// This will automatically clean up threads and memory.

if (hThreadArray[t] == NULL)
{
error("Error create thread");
}

}

// Wait until all threads have terminated.
WaitForMultipleObjects(20, hThreadArray, TRUE, INFINITE);

// Close all thread handles
int i;
for(i = 0; i < 20; i++)
{
CloseHandle(hThreadArray[i]);
}

printf(" Теперь осталось %i бутылок пива на стене\n", beers);

CloseHandle(hMutex);
return 0;
}

to be continued...