3

Consider this code that works, where I intend to move a resource to a new thread:

void Func1(std::ofstream* f) {
    std::unique_ptr<std::ofstream> file(f);

    *file << "This is working" << std::endl;
}

int Func2() {
    std::unique_ptr<std::ofstream> file(new std::ofstream("output.txt"));

    std::thread t1(&Func1, file.release());
    t1.detach();

    return 0;
}

int main() {

    Func2();

    std::cin.get();

    return 0;
}

Since I don't find a way to move a resource across a thread boundary, I have to pass a plain pointer.

Is this the way to go? Would a global variable be better to handle the resource?

Yes, I could pass the filename and open it at Func1, but the question is generic to any kind of class that should not be copied.

nunojpg
  • 505
  • 3
  • 16
  • 1
    Could you explain complications of passing smart pointer `std::unique_ptr` directly? My C++ got rusty and this might be useful for future readers too. – Basilevs Sep 06 '14 at 16:15
  • You can't pass it be value (it must be a & or &&), and it could go out of scope and destroyed before Func1 would try o get the guts from it. – nunojpg Sep 06 '14 at 16:22
  • Aren't [arguments copied by value](http://en.cppreference.com/w/cpp/thread/thread/thread)? See "Notes" section. – Basilevs Sep 06 '14 at 16:25
  • I'm not sure if I'm getting you. Both std::ofstream and std::unique_ptr are resources in the sense that their duplication is not allowed. For this reason they must be necessarily "moved", and the question is not even about performance. – nunojpg Sep 06 '14 at 16:33
  • 1
    possible duplicate of [boost::thread and std::unique\_ptr](http://stackoverflow.com/questions/6398430/boostthread-and-stdunique-ptr) – Basilevs Sep 06 '14 at 16:34
  • Ok, found the answer for you :) It was in "Related" column on the right. – Basilevs Sep 06 '14 at 16:34
  • Related [Is unique_ptr thread safe](http://stackoverflow.com/questions/11482580/is-unique-ptr-thread-safe) – Basilevs Sep 11 '14 at 16:41

1 Answers1

3
void Func1(std::unique_ptr<std::ofstream> file) {

    *file << "This is working" << std::endl;
}

int Func2() {
    std::unique_ptr<std::ofstream> file(new std::ofstream("output.txt"));

    std::thread t1(&Func1, std::move(file));
    t1.detach();

    return 0;
}

Inspired by boost::thread and std::unique_ptr

Community
  • 1
  • 1
Basilevs
  • 22,440
  • 15
  • 57
  • 102