История изменений
Исправление Rot1, (текущая версия) :
Так хотелось?
#include <iostream>
#include <future>
#include <chrono>
#include <string>
#include <mutex>
std::mutex ptmtx;
void foo();
void bar();
void print(const std::string&);
int main()
{
// future обязательно нужно принять
auto a = std::async(std::launch::async, foo);
auto b = std::async(std::launch::async, bar);
a.wait();
b.wait();
std::cout << "Main" << std::endl;
return 0;
}
void foo()
{
while(true) {
std::this_thread::sleep_for(std::chrono::seconds {2});
print("_Foo");
}
}
void bar()
{
while(true) {
std::this_thread::sleep_for(std::chrono::seconds {2});
print("__Bar");
}
}
void print(const std::string& msg)
{
std::lock_guard locker {ptmtx};
std::cout << msg << std::endl;
}
[vanya@Alyona async]$ g++ -std=c++17 -lpthread main.cpp && ./a.out
_Foo
__Bar
_Foo
__Bar
_Foo
__Bar
^C
[vanya@Alyona async]$
чтобы ещё и кроссплатформенно
Все из стандарта, поэтому, грубо говоря, кроссплатформенно
Исправление Rot1, :
Так хотелось?
#include <iostream>
#include <future>
#include <chrono>
#include <string>
#include <mutex>
std::mutex ptmtx;
void foo();
void bar();
void print(const std::string&);
int main()
{
// future обязательно нужно принять
auto a = std::async(std::launch::async, foo);
auto b = std::async(std::launch::async, bar);
a.wait();
b.wait();
std::cout << "Main" << std::endl;
return 0;
}
void foo()
{
while(true) {
std::this_thread::sleep_for(std::chrono::seconds {2});
print("_Foo");
}
}
void bar()
{
while(true) {
std::this_thread::sleep_for(std::chrono::seconds {2});
print("__Bar");
}
}
void print(const std::string& msg)
{
std::lock_guard locker {ptmtx};
std::cout << msg << std::endl;
}
чтобы ещё и кроссплатформенно
Все из стандарта, поэтому, грубо говоря, кроссплатформенно
Исходная версия Rot1, :
Так хотелось?
#include <iostream>
#include <future>
#include <chrono>
#include <string>
#include <mutex>
std::mutex ptmtx;
void foo();
void bar();
void print(const std::string&);
int main()
{
// future обязательно нужно принять
auto a = std::async(std::launch::async, foo);
auto b = std::async(std::launch::async, bar);
a.wait();
b.wait();
std::cout << "Main" << std::endl;
return 0;
}
void foo()
{
while(true) {
std::this_thread::sleep_for(std::chrono::seconds {2});
print("_Foo");
}
}
void bar()
{
while(true) {
std::this_thread::sleep_for(std::chrono::seconds {2});
print("__Bar");
}
}
void print(const std::string& msg)
{
std::lock_guard locker {ptmtx};
std::cout << msg << std::endl;
}
чтобы ещё и кроссплатформенно
Все из стандарта, поэтому, грубо говоря, кроссплатформенно