Cesar
Cesar

Reputation: 527

Run 2 threads indefinitly with join

What's the best practice to achieve this :

And those, indefinitely

while (true) {
        thread tGatherData(getData); // Get data 
        tGatherData.join();          // Wait for data
        thread tRender(render);      // Render data
        Sleep(3);
}

Using it like this doesn't sound like a good practice because it creates a new thread everytime right ?

How should I proceed ? Thanks

Upvotes: 1

Views: 90

Answers (1)

Deumaudit
Deumaudit

Reputation: 1016

If you don't want to create thread on each iteration of your loop, you may want to start 2 threads: one for gathering information, second for printing it, and place your loop in both threads(you should remember about synchronization)

For example here I've created two threads: first for reading from console, second for printing. Synchronization is done by atomic. The program will stop execution, when it reads 0.

But, as good as I understand your code, you don't need second thread at all. All You need is to place your render function inside main thread. And your gathering function isn't asynchronous. It just create another thread and instantly start to wait for it's finishing, so your program should be single thread

Upvotes: 3

Related Questions