本文介绍了在GCC中关闭COW的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道GCC对 std :: string 使用COW(Copy-On-Write),使得不可能使用 std :: string 。但是据我所知C ++ 11禁止使用COW的实现,因为线程现在由标准定义,并且移动语义几乎已经过时了对COW的需要。

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.

现在,GCC 4.6实现了大量的C ++ 11标准。然而,似乎实现仍然使用COW语义。这是通过在我写的多线程应用程序中随机出现的神秘段错误引起我注意的。我确认这是,事实上,通过以下测试代码COW问题:

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());
}



修改注意这里包括< thread> 头,证明这是一个C ++ 11程序。这里是,确认我在说什么(至少对于ideone使用的GCC 4.5.1)


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)

我不记得为什么,但由于某种原因,我的印象是 std = c ++ 0x 标志会消除COW语义,但它不。上述代码中的断言是成功的,即使使用--std = c ++ 0x标志。因此,基本上,从GCC 4.6开始, std :: string 在多线程应用程序中仍然不可用。

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.

有没有办法禁用COW语义?或者我需要使用 std :: vector< char> 直到GCC解决这个问题吗?

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

推荐答案

如果你要在一个线程边界传递一个字符串,做一个明确的副本,以强制它是一个独立的字符串,然后传递:

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());

在交叉线程的所有地方都要这样做很烦人,但在我看来, 向量< char>

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>.

这篇关于在GCC中关闭COW的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 21:14