Hello i am trying to run two functions at the same time. Because i want to learn to make a timer or countdown of some kind.
And i have an idea on how to do so. But when i create two threads.
I get no output in my console application.
Here is my code.
#include <iostream>
#include <Windows.h>
#include <thread>
#include <random>
#include <string>
void timer()
{
int x{ 0 };
if (x < 1000)
{
std::cout << x ;
Sleep(1000);
}
}
void timer2()
{
int x{ 0 };
if (x < 10000)
{
std::cout << x ;
Sleep(1000);
}
}
int main()
{
std::thread one(timer);
std::thread two(timer2);
one.detach();
two.detach();
return 0;
}
CodePudding user response:
You should use join
instead of detach
. Otherwise, the main thread won't wait for the other threads and the program will exit almost immediately. You can use std::this_thread::sleep_for
instead of Sleep
to make the code portable (no Windows.h
required).
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
void timer()
{
int x{ 0 };
if (x < 1000)
{
std::cout << x ;
std::this_thread::sleep_for(1s);
}
}
void timer2()
{
int x{ 0 };
if (x < 10000)
{
std::cout << x ;
std::this_thread::sleep_for(1s);
}
}
int main()
{
std::thread one(timer);
std::thread two(timer2);
one.join();
two.join();
return 0;
}
CodePudding user response:
You need to flush the output. C won't output anything until it flushes. You can achieve this by
cout << x << "\n";
or
cout << x << std::flush;
according to this answer