使用Boost 1.55线程和文件系统并发内存损坏(Visual Studio 2013)

Concurrency memory corruption using Boost 1.55 Thread and Filesystem (Visual Studio 2013)

本文关键字:损坏 Visual Studio 2013 内存 并发 Boost 线程 文件系统 使用      更新时间:2023-10-16

我有以下代码:

#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <thread>
#define BOOST_THREAD_DYN_LINK
#include "boost/filesystem.hpp"
#include "boost/thread/thread.hpp"
using namespace std;
void testEx(std::string & name){
    while (1){
        boost::filesystem::path perc(name);
        if (boost::filesystem::exists(perc))
            cout << "yes" << endl;
    }
}
int main(){
    std::string name = "c:\text.txt";
    vector<boost::thread> pool;
    for (int i = 0; i < 10;i++)
        pool.emplace_back(testEx, name);
    while (1){
        std::ofstream out(name, std::ios_base::out | std::ios_base::app);
        out << "a" << std::endl;
        out.close();
    }
    for (auto & t : pool)
        t.join();
}

主线程正在写文件。对于子线程,我检查文件是否存在。当我创建一个boost::filesystem::path实例时,程序经常因为内存损坏而崩溃。

如果我使用std::thread而不是boost::thread,程序可以正常工作。

我能做些什么来让这个程序工作与boost::线程(很多遗留代码)。为什么会发生这种情况?

现在我通过动态链接boost::filesystem来解决

#define BOOST_FILESYSTEM_DYN_LINK

只是一个变通