Purixi
Purixi

Reputation: 139

How do I use while true in threads?

Can anyone point me at the thing I try to do in this code, because SecondLoop thread is unreachable at all? It becomes reachable only if I remove while(true) loop.

#include <iostream>
#include <thread>

using namespace std;

void Loop() {
    while(true) {
        (do something)
    }
}

void SecondLoop() {
    while(true) {
        (do something)
    }
}

int main() {
    thread t1(Loop);
    t1.join();

    thread t2(SecondLoop);
    t2.join(); // THIS THREAD IS UNREACHABLE AT ALL!

    return false;
}

The reason why I use multithreading is because I need to get two loops running at the same time.

Upvotes: 7

Views: 18761

Answers (5)

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

join blocks the current thread to wait for another thread to finish. Since your t1 never finishes, your main thread waits for it indefinitely.

Edit:

To run two threads indefinitely and concurrency, first create the threads, and then wait for both:

int main() {
    thread t1(Loop);
    thread t2(SecondLoop);

    t1.join();
    t2.join();
}

Upvotes: 15

CJCombrink
CJCombrink

Reputation: 3950

Based on my comment and what @Nidhoegger answered I suggest:

int main() {
    thread t1(Loop);
    thread t2(SecondLoop);
    // Your 2 threads will run now in paralel
    // ... <- So some other things with your application
    // Now you want to close the app, perhaps all work is done or the user asked it to quit
    // Notify threads to stop
    t1running = false;
    t2running = false;
    // Wait for all threads to stop
    t1.join();
    t2.join(); 
    // Exit program
    return false;

}

Upvotes: 0

Jarod42
Jarod42

Reputation: 217235

To run Loop and SecondLoop concurrency, you have to do something like:

#include <iostream>
#include <thread>

void Loop() {
    while(true) {
        //(do something)
    }
}

void SecondLoop() {
    while(true) {
        //(do something)
    }
}

int main() {
    std::thread t1(Loop);
    std::thread t2(SecondLoop);
    t1.join();
    t2.join();
}

as join block current thread to wait the other thread finishes.

Upvotes: 2

Rocky Manganye
Rocky Manganye

Reputation: 65

using while(true) is linked to the tread running , you should look for a way to exit that loop, use some sort of loop control

Upvotes: 0

pewpew
pewpew

Reputation: 39

.join() waits for the thread to end (so in this case if you break out of the while loops and exit the thread function)

Upvotes: 1

Related Questions