Columbo
Columbo

Reputation: 2936

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:

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

Upvotes: 2

Views: 1798

Answers (1)

sehe
sehe

Reputation: 393969

Not tested, but try std::ref.

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. Consider adding synchronization for the output stream...

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)

Upvotes: 1

Related Questions