gpt4 book ai didi

c++ - 使用构造函数参数将仿函数传递给 std::thread。是否可以?

转载 作者:太空狗 更新时间:2023-10-29 20:38:04 26 4
gpt4 key购买 nike

class worker {
std::atomic_bool done;
std::string segment_name;
bi::named_mutex mutex;
std::string file_name;
data_segment_state state;
unsigned long data_size;
std::unique_ptr<unsigned char> data;
protected:
void operator()() {
while(!done) {
}
}

public:
worker(const std::string& _segment_name, bi::managed_shared_memory& segment)
: done{false},
segment_name{_segment_name},
mutex{bi::open_or_create, segment_name.c_str() },
file_name {},
state {data_segment_state::not_received },
data_size{0},
data {segment.construct<unsigned char>(segment_name.c_str())[chunk_size](0) }
}

worker(worker&& rhs)
: done {rhs.done.load()} ,
mutex(bi::open_or_create, rhs.segment_name.c_str()),
segment_name{rhs.segment_name},
file_name {rhs.file_name},
state {rhs.state },
data_size{rhs.data_size},
data {std::move(rhs.data)} {
}
};

...

 std::string worker_name;
std::thread t{worker{worker_name, segment}};

In instantiation of 'struct std::_Bind_simple<worker()>':
thread:137:47: required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = worker; _Args = {}]'
error: no type named 'type' in 'class std::result_of<worker()>'
typedef typename result_of<_Callable(_Args...)>::type result_type;

什么是函数对象的有效线程初始化?错误全文: 错误:“class
”中没有名为“type”的类型 std::result_of' typedef typename result_of<_Callable(_Args...)>::type result_type; ^

最佳答案

只需传递构造的仿函数:

std::thread t(worker{str, 10});

Live demo

constructor of std::thread您指的是采用构造的函数对象和调用该函数对象时将传递的参数。因此,在您的情况下,参数将传递给 operator()

关于c++ - 使用构造函数参数将仿函数传递给 std::thread。是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32887403/

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