std::move_only_function线程安全吗?

问题描述 投票:0回答:1

在一个线程中调用

std::move_only_function
对象并在另一个线程中替换它指向的函数是否安全?

我的代码:

#include <future>
#include <functional>

int main() {
    std::move_only_function<void()> fn = []{};

    auto future1 = std::async(std::launch::async, [&]{ fn(); });
    auto future2 = std::async(std::launch::async, [&]{ fn = []{}; });

    future1.get();
    future2.get();
}

我不在乎是调用旧函数还是新函数。我还知道

fn
始终具有有效的功能。

c++ multithreading std c++23
1个回答
0
投票

不,这不安全。
赋值运算符 (

std::move_only_function::operator=
) 不保证是原子的。

© www.soinside.com 2019 - 2024. All rights reserved.