C++ - How to have multiple threads write to a file

后端 未结 2 972
自闭症患者
自闭症患者 2021-02-04 17:10

I am currently writing a c++ program that uses threads to write strings to a file. I am using ofstream to write these strings, and I noticed that only one of the threads has acc

2条回答
  •  一向
    一向 (楼主)
    2021-02-04 17:20

    Having multiple threads to write to the same file can lead to some serious troubles. You can try synchronizing the process of writing, by using critical section, for example(using OpenMP):

    #pragma omp critical [(name)]
    {
       write_to_file
    }
    

    or using WinApi: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686908(v=vs.85).aspx

提交回复
热议问题