簡體   English   中英

ofstream變量不能出現在OpenMP firstprivate中?

[英]ofstream variable cannot appear in OpenMP firstprivate?

ofstream myfile("file_path");
#pragma omp parallel for default(none) schedule(dynamic) firstprivate(myfile) private(i)
for(i=0; i<10000; i++) {
    myfile<<omp_get_thread_num()+100<<endl;
}

但編譯器顯示錯誤:

錯誤:使用已刪除的函數'std :: basic_ofstream <_CharT,_Traits> :: basic_ofstream(const std :: basic_ofstream <_CharT,_Traits>&)[with _CharT = char; _Traits = std :: char_traits]'

/ usr / include / c ++ / 5 / fstream:723:7:注意:這里聲明為basic_ofstream(const basic_ofstream&)= delete;

錯誤:'myfile'未在封閉並行中指定

firstprivate通過制作值的線程私有副本來工作。 這不適用於流,因為您無法復制它們。 您只能通過打開多個流來安全地寫入文件。 基本上有兩種選擇:

  • 擁有共享流 ,使用#pragma omp critical保護對它的所有線程訪問。

     ofstream myfile("file_path"); #pragma omp parallel for for (int i=0; i < 10000; i++) { #pragma omp critical myfile << (omp_get_thread_num()+100) << endl; } 
  • 另一個文件上的每個線程打開一個流。

     #pragma omp parallel { ofstream myfile(std::string("file_path.") + std::to_string(omp_get_thread_num())); #pragma omp for for (int i=0; i < 10000; i++) { myfile << (omp_get_thread_num()+100) << endl; } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM