0

Was going through some tutorials on multi-threading and wrote some code to create an infinite thread. However, the infinite loop doesn't seem to work. The print routine inside the loop just runs once. Find the code below for reference. Cant understand what I am doing wrong. I am using the MSVC compiler.

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


DWORD __stdcall ThreadProc(LPVOID lpParameter) {

    const char* StringToPrint = (const char*)lpParameter;

    //expected this block to run infinitely.
    while (1) {
        std::cout << StringToPrint << "\n";
        Sleep(1000);
    }

    return 0;
}


int main() {

    DWORD ThreadId = 0;
    const char *Param = "Inside Thread";
    LPVOID Param1 = (LPVOID)Param;


    HANDLE Threadhandle = CreateThread(0, 0, ThreadProc, Param1, 0, &ThreadId);
    std::cout << "Thread ID " << ThreadId << " started" << "\n";
    CloseHandle(Threadhandle);
    return 0;

}
user1720897
  • 1,216
  • 3
  • 12
  • 27

1 Answers1

2

The loop appears to run once because your program terminates just after you've started the thread.

If you want the thread to run forever, wait for it to finish in the main function:

    HANDLE Threadhandle = CreateThread(0, 0, ThreadProc, Param1, 0, &ThreadId);
    std::cout << "Thread ID " << ThreadId << " started" << "\n";
    WaitForSingleObject(Threadhandle, INFINITE);
    CloseHandle(Threadhandle);                    // it will never reach this
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108