Turning off COW in GCC

…衆ロ難τιáo~ 提交于 2019-12-18 12:15:51

问题


I've known for a while that GCC uses COW (Copy-On-Write) for std::string, making it impossible to use std::string in a multi-threaded program. But as far as I know C++11 prohibits an implementation from using COW, because threads are now defined by the standard, and move semantics pretty much obsolete the need for COW anyway.

Now, GCC 4.6 implements a great deal of the C++11 standard. Yet it seems that the implementation is still using COW semantics. This was brought to my attention by randomly occurring mysterious seg-faults in a multi-threaded application I wrote. I've confirmed this is, in fact, a COW issue via the following test code:

#include <iostream>
#include <string>
#include <cassert>
#include <thread>
using namespace std;

int main()
{
    std::string orig = "abc";
    std::string copy = orig;
    std::cout << (void*) orig.data() << ", " << (void*) copy.data() << endl;
    assert(orig.data() == copy.data());
}


Edit: Note the inclusion of the <thread> header here, proving this is a C++11 program. And here's a link to ideone confirming what I'm saying, (at least for GCC 4.5.1 which ideone uses)

I don't remember why, but for some reason I was under the impression that the std=c++0x flag would eliminate the COW semantics, but it doesn't. The assertion in the above code is successful, even with the --std=c++0x flag. So basically, as of GCC 4.6, std::string is still unusable in a multi-threaded application.

Is there any way to disable COW semantics? Or do I need to use std::vector<char> for now until GCC fixes this?


回答1:


If you're going to pass a string across a thread boundary, do an explicit copy, in order to force it to be an independent string, then pass that across:

std::string a="bob";
std::string b(a.data(), a.length());

It's annoying to have to do this at all spots where things cross threads, but in my opinion it's easier than vector<char>.



来源:https://stackoverflow.com/questions/12430598/turning-off-cow-in-gcc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!