gpt4 book ai didi

c++ - 为什么无法通过 Call-by-Value 将 mutex 传递给 function?

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:36 24 4
gpt4 key购买 nike

Full source code

如果我在没有引用的情况下将互斥对象传递给 worker(),则会导致编译错误。

void worker(int& p_counter, std::mutex p_mutex) {
...
}

=============================================================================

workers.push_back(std::thread(worker, std::ref(counter), mutex));

但是如果我通过引用传递它,它编译得很好。

void worker(int& p_counter, std::mutex& p_mutex) {
...
}

=============================================================================

workers.push_back(std::thread(worker, std::ref(counter), std::ref(mutex)));

为什么实现互斥量以使用引用传递给函数?

最佳答案

If I pass mutex object to worker() without reference, it causes compile error

那是因为 std::mutex 是一个不可复制的类。

Why is mutex implemented to be passed to functions using references?

没有理由按值传递 std::mutex 的对象(并因此复制它),因为互斥量应该用于互斥以防止竞争条件(接收它的函数应该能够引用与调用者传递的对象相同的互斥对象)。

关于c++ - 为什么无法通过 Call-by-Value 将 mutex 传递给 function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57644698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com