c++multithreadingprotectedstdasyncstdmutex

Is there a need to provide a std::mutex for std::async?


As stuff I mentioned above, Should I prodive a std::mutex for std::async in the following section? :

#include <vector>
#include <future>
#include <mutex>
#include <ranges>

int main()
{
    [[maybe_unused]] result=::std::async([&]
    {
        ::std::mutex s{};

        ::std::vector<int> f{};

        ::std::ranges::for_each(::std::views::iota(1) | ::std::views::take(10) | ::std::views::filter([&](const auto& iter) { return 0 == 2 % iter; }), [&](const auto& iter)
            {
                {
                    std::unique_lock guard{ s };
                    
                    f.push_back(iter);
                }
            });
    });

    return 0;
}

Can someone give a anwser to this problem in details? thanks!


Solution

  • As @Aconcagua's answered above, there is no need for giving a ::std::mutex for vector.Owing to ranges was strictly executed in order. Thanks Aconcagua for your interpretation.