I am using c++, and want to do asynchronous programming. I tried the following code:
#include <thread>
#include <chrono>
#include <iostream>
#include <future>
void f(int id) {
switch (id) {
case 28: {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
break;
}
case 9: {
std::async(f, 28); //I am using std::async instead of std::thread because I want to get a return value from it in my real code
break;
}
}
std::cout << "Test For " << id << std::endl;
}
int main() {
f(9);
}
and this prints
Test For 28
Test For 9
(and the entire message gets printed after 1 second) What i want to happen is
Test For 9
Test For 28
(and I want the two messages to be printed 1 second from each other)
then I tried to do it wil 100000 milliseconds, but the same thing happens (except it takes much longer).
is there a reason for this not happening?
this also does not work
#include <thread>
#include <chrono>
#include <iostream>
#include <future>
int f(int id) {
switch (id) {
case 28: {
std::this_thread::sleep_for(std::chrono::milliseconds(100000));
break;
}
case 9: {
std::future<int> a = std::async(f, 28);
break;
}
}
std::cout << "Test For " << id << std::endl;
return 0;
}
int main() {
f(9);
}
as it produced the same result