我試圖將多個參數(其中之一是ofstream
對象)傳遞給使用C++11
標準的多個線程。將輸出流對象和其他參數傳遞給多個線程
我想通過一個ofstream
對象,因爲我希望每個線程寫入不同的輸出文件。
我初始化線程和輸出流以這樣的方式
std::thread execution_threads[NUMBER_OF_THREADS]; // creating multiple empty threads
std::ofstream output_files[NUMBER_OF_THREADS]; // Empty output streams
// Opening and initializing the output files
每個線程執行的函數有兩個參數:
void execution(int thread_id, std::ofstream& output_file)
所以我環顧四周,我」已經閱讀C++11
當函數func
有多個參數a,b,c,d
時,不需要使用struct
,只需編寫std::thread t(func, a,b,c,d);
就可以傳遞它們。所以,我爲了啓動線程寫這個循環:
for (int i = 0; i < utils::NUMBER_OF_THREADS; i++) {
execution_threads[i] = std::thread(execution, i, output_files[i]);
}
的事情是,這個代碼不與此錯誤編譯:
Call to implicitly-deleted copy constructor of
'typename decay<basic_ofstream<char, char_traits<char> > &>::type'
(aka 'std::__1::basic_ofstream<char, std::__1::char_traits<char> >')
而如果我在使用struct
作爲輸入方式,一切工作正常:
// Struct definition
struct thread_input {
int thread_id;
std::ofstream& output_file;
};
// This is the function that now has only one argument
void execution(struct thread_input input)
// And this is the loop that launches the threads
for (int i = 0; i < utils::NUMBER_OF_THREADS; i++) {
struct thread_input input = {i, output_files[i]};
execution_threads[i] = std::thread(execution, input);
}
// join() functions for each thread and end of the program
這樣一切工作正常,它編譯和它運行完美。但我真的不知道爲什麼編譯器告訴我,如果我使用另一種方法,我正嘗試使用已刪除的副本構造函數。
謝謝你的幫助。