Skip to main content

Command Palette

Search for a command to run...

Folly::future V.S. std::future

Updated
1 min read
N

I’m a backend developer based in Beijing, passionate about crafting efficient and scalable solutions. Amidst my coding endeavors, I’ve embarked on an exciting journey as an active English learner. Exploring the intricacies of language allows me to broaden my horizons and connect with diverse communities worldwide. Join me as I navigate the realms of technology and language, striving for excellence in both.

#include <future>
#include <iostream>
#include <thread>

int main()
{
    // future from a packaged_task
    std::packaged_task<int()> task([]{ return 7; }); // wrap the function
    std::future<int> f1 = task.get_future(); // get a future
    std::thread t(std::move(task)); // launch on a thread

    // future from an async()
    std::future<int> f2 = std::async(std::launch::async, []{ return 8; });

    // future from a promise
    std::promise<int> p;
    std::future<int> f3 = p.get_future();
    std::thread([&p]{ p.set_value_at_thread_exit(9); }).detach();

    std::cout << "Waiting..." << std::flush;
    f1.wait();
    f2.wait();
    f3.wait();
    std::cout << "Done!\nResults are: "
              << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
    t.join();
}

Appending some syntax a

Capture Clause: The capture clause is the part inside the square brackets [ ] in a lambda expression. It determines how variables from the surrounding scope are accessed inside the lambda. There are several ways to capture variables:

[&]: Capture all variables by reference.
[=]: Capture all variables by value.
[p]: Capture the variable p by value.
[&p]: Capture the variable p by reference.
[=, &p]: Capture all variables by value, but capture p by reference.
[&, p]: Capture all variables by reference, but capture p by value.

Reference

  1. Facebook Future Blog

  2. cppreference.com std::future

55 views

More from this blog

W

Way to far away

10 posts

I’m a backend developer based in Beijing, passionate about crafting efficient and scalable solutions. Amidst my coding endeavors, I’ve embarked on an exciting journey as an active English learner.