考虑这个方案,基本上创建std::thread调用该函数func()以arg作为参数:
#include <thread>
#include <iostream>
struct foo {
foo() = default;
foo(const foo&) { std::cout << "copy ctor" << std::endl; }
foo(foo&&) noexcept { std::cout << "move ctor" << std::endl; }
};
void func(foo){}
int main() {
foo arg;
std::thread th(func, arg);
th.join();
}
Run Code Online (Sandbox Code Playgroud)
我的输出是
copy ctor
move ctor
move ctor
Run Code Online (Sandbox Code Playgroud)
据我了解arg是在线程对象内部复制,然后func()作为右值传递给(移动)。所以,我期望一个副本构造和一个移动构造。
为什么要进行二次施工?
在 C++14 中有shared_lock作为reader-writer lock。这必须与shared_mutex. 例子:
// my shared data
std::shared_mutex mut;
Data data;
void process_data(const Data *); // read-only function
void update_data(Data *);
// multiple threads can read data
void read_data(){
std::shared_lock lk(mut);
process_data(&data);
}
// only one thread can read data
void write_data(){
std::unique_lock lk(mut); // exclusive lock
update_data(&data);
}
Run Code Online (Sandbox Code Playgroud)
据我所知shared_mutex是在C++17shared_lock中引入的,比在C++14 中引入的晚。您不能使用shared_lock没有shared_mutex。
shared_locked如果当时没有shared_mutex,为什么要在 C++14 中引入?