[英]passing functor to std::thread with ctor parameters. is it possible?
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;
什么是功能對象的有效線程初始化? 錯誤的全文:錯誤:'類中沒有名為'type'的類型
std :: result_of'typedef typename result_of <_Callable(_ Args ...)> :: type result_type; ^
只需傳遞構造的仿函數:
std::thread t(worker{str, 10});
您引用的std::thread
的構造函數接受一個構造的函數對象和在調用該函數對象時將傳遞的參數。 因此,在您的情況下,參數將傳遞給operator()
。
問題在於我的疏忽:operator()在受保護的部分。 搬到公眾解決問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.