Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
Purixi Avatar asked Oct 30 '15 08:10

Purixi


People also ask

Does Python have true threading?

Python is NOT a single-threaded language. Python processes typically use a single thread because of the GIL. Despite the GIL, libraries that perform computationally heavy tasks like numpy, scipy and pytorch utilise C-based implementations under the hood, allowing the use of multiple cores.

How do you use multiple threads in Python?

To use multithreading, we need to import the threading module in Python Program. A start() method is used to initiate the activity of a thread. And it calls only once for each thread so that the execution of the thread can begin.

What is daemon thread in Python?

The threads which are always going to run in the background that provides supports to main or non-daemon threads, those background executing threads are considered as Daemon Threads. The Daemon Thread does not block the main thread from exiting and continues to run in the background.

How do you create a new thread in Java?

Creating and Starting ThreadsThread thread = new Thread(); To start the Java thread you will call its start() method, like this: thread. start();


2 Answers

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();
}
like image 105
SingerOfTheFall Avatar answered Oct 21 '22 20:10

SingerOfTheFall


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.

like image 28
Jarod42 Avatar answered Oct 21 '22 21:10

Jarod42