I have a function that I want to run it inside another function, so the main function I have , have a while loop running and the other function outside also have a while loop, and I wanna run both together without any of each other interrupting each other,
so the main function will keep its main while loop running normally and the other function.
I want it to run as a thread in the background but only inside IF statement and its also a while loop and only if this IF statement was TRUE it will start the thread and will also run while the main loop function running I will show here the problem by example:
void MatchChecker()
{
while (1)
{
if (g_pOBJ->checkInMatch() == 2)
{
std::cout << "In Match! " << std::endl;
}
}
void mainFunc()
{
while (1)
{
if (checkIngame() == true) {
std::thread checker(MatchChecker);
checker.join();
break;
}
}
while (1)
{
std::cout << "Im doing some stuff here in this main loop" << std::endl;
someOtherThread.join();
}
}
so the main problem is with the checker.join();
when I add it inside that if , the second loop doesn't start and its stuck with the mainchecker loop, and I cant put the checker.join
inside the other loop because its not defined, so what can I do to solve my problem? any suggestions?
CodePudding user response:
If you want to run 2 threads concurrently, but let's say the execution of one of them is subject to a condition, you could maybe do the following:
- Run the one whose execution is subject to a condition as an async task. This way, you can declare a future for that task and later check if that future is valid (i.e. if a task was created for that future).
- Run the other one in a normal thread (another async task would serve as well).
This way, you can wait in your mainFunc
for your tasks/threads to finish (with a get
on the future and a join
on the thread). Demo
#include <iostream> // cout
#include <future> // async
#include <thread>
void f() { for (auto i{0}; i < 10000; i) std::cout << "a\n"; }
void g() { for (auto i{0}; i < 10000; i) std::cout << "b\n"; }
int main()
{
std::future<void> fut{};
if (0) // 0 just for testing; your condition would come here
{
fut = std::async(std::launch::async, f);
}
std::thread t_g(g);
t_g.join();
if (fut.valid())
{
fut.get();
}
}
CodePudding user response:
ITNOA
You can change your code like below
void MatchChecker()
{
while (1)
{
if (g_pOBJ->checkInMatch() == 2)
{
std::cout << "In Match! " << std::endl;
}
}
void mainFunc()
{
std::thread checker;
while (1)
{
if (checkIngame() == true) {
checker = std::thread(MatchChecker);
break;
}
}
while (1)
{
std::cout << "Im doing some stuff here in this main loop" << std::endl;
someOtherThread.join();
}
if (checker.joinable())
checker.join();
}
In the above code, I separate thread definition and running by define empty thread, and start when I needed.
For gracefully joining thread, in the end of function I check thread is joinable
or not, if it is joinable, I try to join
it.