gpt4 book ai didi

c++ - 标准容器作为多线程应用程序中的局部变量

转载 作者:IT老高 更新时间:2023-10-28 23:15:15 27 4
gpt4 key购买 nike

我知道标准库中的容器不是线程安全的。我曾经认为一个容器,比如 std::list 类型的容器,不能被多个线程同时访问(其中一些可能会修改容器)。但现在看来,它的意义远不止眼前所见;更微妙的东西,不是那么明显的东西,至少对我来说是这样。

例如,考虑这个接受第一个参数的函数按值:

void log(std::string msg, severity s, /*...*/) 
{
return; //no code!
}

这是线程安全的吗?

起初,它似乎是线程安全的,因为函数体不访问共享的可修改资源,因此是线程安全的。再想一想,当我调用这样一个函数时,会创建一个 std::string 类型的对象,这是第一个参数,我认为这个对象的构造不是t 线程安全,因为它在内部使用 std::allocator,我认为这不是线程安全的。因此调用这样的函数也不是线程安全的。但如果它是正确的,那么这个呢:

void f()
{
std::string msg = "message"; //is it thread-safe? it doesn't seem so!
}

我走对了吗?我们可以在多线程程序中使用 std::string (或任何内部使用 std::allocator 的容器)吗?

我专门将容器称为局部变量,而不是共享对象。

我搜索了谷歌,发现了很多类似的疑问,没有具体的答案。我面临与他类似的问题:

请同时考虑 C++03 和 C++11。

最佳答案

在 C++11 中,std::allocator 是线程安全的。从它的定义来看:

20.6.9.1/6: Remark: the storage is obtained by calling ::operator new(std::size_t)

::operator new的定义:

18.6.1.4: The library versions of operator new and operator delete, user replacement versions of global operator new and operator delete, and the C standard library functions calloc, malloc, realloc, and free shall not introduce data races (1.10) as a result of concurrent calls from different threads.

C++03 没有线程的概念,因此任何线程安全都是特定于实现的;您必须引用您的实现文档以查看它提供的保证(如果有)。由于您使用的是 Microsoft 的实现,this page表示从多个线程写入同一类的多个容器对象是安全的,这意味着 std::allocator 是线程安全的。

关于c++ - 标准容器作为多线程应用程序中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9521879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com