nunojpg
nunojpg

Reputation: 505

Moving resources to a new thread in a safer manner

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.

Upvotes: 3

Views: 141

Answers (1)

Basilevs
Basilevs

Reputation: 23929

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

Upvotes: 3

Related Questions