I am not understanding how my program is not executing correctly and why I have to use std::this_thread::yield() to make it work.
This code does not print "hello" 1000 times.
#include <iostream>
#include <thread>
bool start = false;
void wait_print_hello()
{
while (!start)
{
}
for (int i = 0; i < 1000; i++)
{
std::cout << "hello" << std::endl;
}
}
void print_one_thousand()
{
for (int i = 0; i < 1000; i++)
{
std::cout << i + 1 << std::endl;
}
start = true;
}
int main()
{
std::thread first(print_one_thousand);
std::thread second(wait_print_hello);
first.join();
second.join();
return 0;
}
This code prints "hello" 1000 times
#include <iostream>
#include <thread>
bool start = false;
void wait_print_hello()
{
while (!start)
{
std::this_thread::yield();
}
for (int i = 0; i < 1000; i++)
{
std::cout << "hello" << std::endl;
}
}
void print_one_thousand()
{
for (int i = 0; i < 1000; i++)
{
std::cout << i + 1 << std::endl;
}
start = true;
}
int main()
{
std::thread first(print_one_thousand);
std::thread second(wait_print_hello);
first.join();
second.join();
return 0;
}
What baffles me even more is that this code prints "hello" 1000 times for me also
#include <iostream>
#include <thread>
bool start = false;
void wait_print_hello()
{
while (!start)
{
std::cout << start << std::endl;
}
for (int i = 0; i < 1000; i++)
{
std::cout << "hello" << std::endl;
}
}
void print_one_thousand()
{
for (int i = 0; i < 1000; i++)
{
std::cout << i + 1 << std::endl;
}
start = true;
}
int main()
{
std::thread first(print_one_thousand);
std::thread second(wait_print_hello);
first.join();
second.join();
return 0;
}
Why does is it work like this?