简体   繁体   English

将ofstream传递给线程函数

[英]Passing an ofstream to a thread function

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: 我一直在查看线程,并在尝试将对ofstream的引用传递给线程函数时遇到错误:

This is the code: 这是代码:

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 谢谢

Not tested, but try std::ref . 未经测试,但尝试std::ref

rationale : thread constructor uses variadic templates to forward the arguments; 基本原理thread构造函数使用可变参数模板来转发参数; if perfect forwarding is not enabled there 1 , you'll need to wrap the reference so it doesn't get passed by value). 如果没有在 1 启用完美转发,则需要包装引用,以便它不会按值传递)。

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();
} 

PS Consider adding synchronization for the output stream... PS考虑为输出流添加同步...

1 perfect forwarding requires a pack expansion like std::forward<Args>(arguments)... ; 1个完美的转发需要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) 它可能尚未在编译器上实现, 或者可能未被设计使用(以防止在线程之间意外共享数据)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM