I am currently trying out the API from <windows.h> with a simple multi-threaded program that prints each thread's given index in a synchronized manner, with a 1-second delay between each print action.
This program is written in C, but I suppose it will be the same in C++.
And this is the code:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define THREAD_LEN 100
HANDLE mutex_handle = NULL;
HANDLE thread_handle[THREAD_LEN];
DWORD WINAPI execute(LPVOID param) {
int id = *(int *) param;
if (WAIT_OBJECT_0 != WaitForSingleObject(mutex_handle, INFINITE)) {
printf("ERROR_CODE: %d\n", GetLastError());
}
printf("[%d]\n", id);
Sleep(1000);
ReleaseMutex(mutex_handle);
return 0;
}
int main(void) {
mutex_handle = CreateMutex(NULL, FALSE, NULL);
DWORD thread_id;
for (int i = 0; i < THREAD_LEN; i++) {
int *id = (int *) malloc(sizeof(int));
*id = i;
thread_handle[i] = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE) execute,
id,
0,
&thread_id);
if (!thread_handle[i]) {
return 1;
}
}
WaitForMultipleObjects(THREAD_LEN, thread_handle, TRUE, INFINITE);
for (int i = 0; i < THREAD_LEN; i++) {
CloseHandle(thread_handle[i]);
}
CloseHandle(mutex_handle);
return 0;
}
But it shows unexpected behavior: When I run it via cmd, the method Sleep(1000) does not work (The program does not print one id per second, but in a single burst), and not all the threads have their id printed out.
[0]
ERROR_CODE: 6
ERROR_CODE: 6
[30]
ERROR_CODE: 6
[5]
[29]
ERROR_CODE: 6
[33]
ERROR_CODE: 6
[34]
ERROR_CODE: 6
[41]
ERROR_CODE: 6
[37]
ERROR_CODE: 6
ERROR_CODE: 6
[47]
ERROR_CODE: 6
ERROR_CODE: 6
[55]
ERROR_CODE: 6
[43]
ERROR_CODE: 6
[44]
ERROR_CODE: 6
[38]
ERROR_CODE: 6
ERROR_CODE: 6
[17]
ERROR_CODE: 6
[50]
ERROR_CODE: 6
[76]
ERROR_CODE: 6
[11]
[36]
ERROR_CODE: 6
[42]
ERROR_CODE: 6
[57]
ERROR_CODE: 6
[13]
ERROR_CODE: 6
[58]
ERROR_CODE: 6
However, when I reduce the thread count to 60, the program does work within expectation.
[0]
[3]
[2]
[1]
[6]
[34]
[37]
[39]
[8]
[9]
[46]
[11]
[51]
[53]
[55]
[58]
[16]
[17]
[18]
[19]
[20]
[22]
[21]
[23]
[24]
[25]
[26]
[27]
[28]
[29]
[30]
[31]
[32]
[33]
[4]
[36]
[35]
[38]
[5]
[7]
[40]
[42]
[41]
[43]
[44]
[45]
[10]
[47]
[48]
[49]
[50]
[12]
[52]
[13]
[54]
[14]
[56]
[57]
[59]
[15]