将ofstream传递给线程函数 [英] Passing an ofstream to a thread function
问题描述
我一直在查看线程,并在尝试将对ofstream的引用传递给线程函数时遇到错误:
I've been looking at threads and have run into an error when I try to pass a reference to an ofstream to the thread function:
这是代码:
void threader(ofstream& fsOutputFileStream)
{
fsOutputFileStream << "hello";
}
int main()
{
ofstream fsOutputFileStream;
fsOutputFileStream.open("afile.txt", ios::out);
thread t(threader, fsOutputFileStream);
thread u(threader, fsOutputFileStream);
t.join();
u.join();
}
当我尝试编译时,出现此错误:
When I try to compile I get this error:
threadtest.cpp:18: error: initializing argument 2 of âboost::thread::thread(F, A1) [with F = void (*)(std::ofstream&), A1 = std::basic_ofstream<char, std::char_traits<char> >]â
如果我将线程位取出并正常地将引用传递给函数,就没有问题. 任何帮助表示赞赏. 谢谢
If I take the threading bits out and just pass the reference to the function normally there is no problem. Any help appreciated. Thanks
推荐答案
未经测试,但尝试std::ref
.
rationale :thread
构造函数使用可变参数模板来转发参数;如果此处未启用完美转发 1 ,则需要将引用包装起来,这样它就不会按值传递).
rationale: thread
constructor uses variadic templates to forward the arguments; if perfect forwarding is not enabled there1, you'll need to wrap the reference so it doesn't get passed by value).
void threader(ofstream& fsOutputFileStream)
{
fsOutputFileStream << "hello";
}
int main()
{
ofstream fsOutputFileStream;
fsOutputFileStream.open("afile.txt", ios::out);
thread t(threader, std::ref(fsOutputFileStream));
thread u(threader, std::ref(fsOutputFileStream));
t.join();
u.join();
}
P.S.考虑为输出流添加同步...
P.S. Consider adding synchronization for the output stream...
1 完美的转发需要打包扩展,例如std::forward<Args>(arguments)...
;它可能尚未在您的编译器上实现,或它可能未被设计使用(以防止在线程之间意外共享数据)
1 perfect forwarding requires a pack expansion like std::forward<Args>(arguments)...
; It might not yet be implemented on your compiler, or it might not be used by design (to prevent accidentally sharing data between threads)
这篇关于将ofstream传递给线程函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!