0

I wrote a simple example of using a semaphore, but sometimes messages from the first thread are not displayed. What the problem?

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

HANDLE Semaphore;

void test1(void*) {
    WaitForSingleObject(Semaphore, INFINITE);
    std::cout << "Thread1: access granted";
    _endthread();
}

void test2(void*) {
    ReleaseSemaphore(Semaphore, 1, NULL);
    _endthread();
}

int main() {
    Semaphore = CreateSemaphore(NULL, 0, 1, NULL);

    _beginthread(test1, 2048, NULL);
    _beginthread(test2, 2048, NULL);

    CloseHandle(Semaphore);
}

enter image description here

enter image description here

Andrii Matiiash
  • 499
  • 6
  • 18
  • 7
    I don't see anything that will stop main from exiting while the threads are still working away. Thinking something like `WaitForMultipleObjects` is in order to "join" the threads. – user4581301 Sep 07 '17 at 22:19
  • Some details on using beginthread/endthread https://stackoverflow.com/a/31257350/8491726 As such - I would advise never use beginthread/endthread pair - since you are unable to wait for thread exit. Use beginthreadex/endthreadex to strart/end thread and use WaitForSingleObject/WaitForMultipleObjects + CloseHandle to wait for the thread and close handle after wait finished. – Artemy Vysotsky Sep 08 '17 at 04:18
  • Better use std::thread instead of _beginthread and call join to wait for those threads to terminate – Asesh Sep 08 '17 at 05:55
  • I used std::thread and it works well, thanks! – Andrii Matiiash Sep 08 '17 at 18:25

0 Answers0