We will implement a simple application that invokes a long-running function in a separate thread and waits for its result. While the function is running, the application can keep working on other calculations.
- In your ~/test working directory, create a subdirectory called async.
- Use your favorite text editor to create an async.cpp file in the async subdirectory.
- Put the code of our application into the async.cpp file, starting from the common headers and our long-running function:
#include <chrono>
#include <future>
#include <iostream>
int calculate (int x) {
auto start = std::chrono::system_clock::now();
std::cout << "Start calculation\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
auto delta = std::chrono::system_clock::now() - start;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(delta);
std::cout << "Done in " << ms.count() << " ms\n";
return x*x;
}
- Next, add the test function, which invokes the long-running function:
void test(int value, int worktime) {
std::cout << "Request result of calculations for " << value << std::endl;
std::future<int> fut = std::async (calculate, value);
std::cout << "Keep working for " << worktime << " ms" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(worktime));
auto start = std::chrono::system_clock::now();
std::cout << "Waiting for result" << std::endl;
int result = fut.get();
auto delta = std::chrono::system_clock::now() - start;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(delta);
std::cout << "Result is " << result
<< ", waited for " << ms.count() << " ms"
<< std::endl << std::endl;
}
- Finally, add a main minimalistic function:
int main ()
{
test(5, 400);
test(8, 1200);
return 0;
}
- Create a file called CMakeLists.txt in the loop subdirectory, with the following content:
cmake_minimum_required(VERSION 3.5.1)
project(async)
add_executable(async async.cpp)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
SET(CMAKE_CXX_FLAGS "--std=c++14")
target_link_libraries(async pthread -static-libstdc++)
set(CMAKE_CXX_COMPILER /usr/bin/arm-linux-gnueabi-g++)
You can build and run the application.