Camille
Camille

Reputation: 1

C++ how to end a thread called in a while loop?

I have two functions that run simultaneously thanks to thread, both functions write text in two separates files.

void Function1() {
    //Blablabla do stuff
    File1 << My stuff << std::endl;
}

void Function2() {
    //Blablabla do other stuff
    File2 << other stuff << std::endl;
}

int main {
   File1.open();
   File2.open();
   while (true){
        std::thread Th1(Function1);
        std::thread Th2(Function2);

        Th1.join();                
        Th2.join();     
        // I want to end my thread here         
        if (0x01 & GetAsyncKeyState('Q') != 0) {
            // What to put here to safely end function 1 and function 2 ?
            }
        }
    File1.close();
    File2.close();
    return 0;
}

How to end the thread to be able to close the files ? I am new to the use of the class Thread.

Upvotes: 0

Views: 290

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155323

Function1 and Function2 aren't running when you reach the if; you've already joined their threads, so they're done. If you just want to end the infinite loop (preventing the launching of more threads), use break:

    if (0x01 & GetAsyncKeyState('Q') != 0) {
        break;
    }

Upvotes: 1

Related Questions