2014-09-06 50 views
3

考慮這個代碼工作,在那裏我打算在資源移動到一個新的線程:移動資源,以一個新的線程在一個更安全的方式

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

因爲我沒有找到一個方法來移動資源在一個線程邊界上,我必須傳遞一個簡單的指針。

這是要走的路嗎?全局變量會更好地處理資源嗎?

是的,我可以傳遞文件名並在Func1中打開它,但是這個問題對於任何不應該被複制的類都是通用的。

+1

啓發你能解釋一下傳遞智能指針'的std ::的unique_ptr <的std :: ofstream的>'直接的併發症?我的C++生鏽了,這對未來的讀者也可能有用。 – Basilevs 2014-09-06 16:15:51

+0

你不能將它傳遞給它的值(它必須是一個&& &&),它可能超出範圍,並在Func1試圖從它得到它的膽量之前銷燬。 – nunojpg 2014-09-06 16:22:30

+0

不是[通過值複製的參數](http://en.cppreference.com/w/cpp/thread/thread/thread)?請參閱「註釋」部分。 – Basilevs 2014-09-06 16:25:21

回答

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

通過boost::thread and std::unique_ptr

相關問題