std::map中的值是否可以被锁定?
Can a value in std::map for a key be locked?
我有一个具有key-value的简单std::map。我希望这个map是线程安全的。我不想锁定整个地图。因为我的线程只对map中特定键的值进行操作(更新、删除),所以我不希望锁定整个map。我希望其他线程能够在地图上工作,当然不是锁定值。
只锁定特定键的值是可取的还是逻辑上正确的?或者我应该考虑另一种数据结构?
更新:我刚刚尝试了一个示例示例,其中我有并行线程更新和插入在同一地图。
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <map>
#include <process.h>
#include <windows.h>
using namespace std;
CRITICAL_SECTION CriticalSection;
struct newEntry
{
int key;
char value;
};
std::map<int,char> mapIntChar;
unsigned __stdcall UpdateThreadFunc( void* pArguments )
{
char *ptr = (char *) pArguments;
EnterCriticalSection(&CriticalSection);
*ptr = 'Z';
LeaveCriticalSection(&CriticalSection);
_endthreadex( 0 );
return 0;
}
unsigned __stdcall InsertThreadFunc( void* pArguments )
{
struct newEntry *ptr = (struct newEntry *) pArguments;
mapIntChar[ptr->key] = ptr->value;
_endthreadex( 0 );
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::map<int,char>::iterator it1;
unsigned threadID;
if (!InitializeCriticalSectionAndSpinCount(&CriticalSection,
0x00000400) )
return 0;
mapIntChar[0] = 'A';
mapIntChar[1] = 'B';
mapIntChar[2] = 'C';
mapIntChar[3] = 'D';
HANDLE hThread;
int nCount = 0;
struct newEntry *newIns;
while ( nCount < 1004)
{
it1 = mapIntChar.begin();
char *ptr = &(it1->second);
hThread = (HANDLE)_beginthreadex( NULL, 0, &UpdateThreadFunc, ptr, 0, &threadID );
newIns = new newEntry;
newIns->key = rand() % 1000;
newIns->value = 'K';
hThread = (HANDLE)_beginthreadex( NULL, 0, &InsertThreadFunc, newIns, 0, &threadID );
nCount++;
delete newIns;
}
}
您可以在std::map
周围创建一个包装器(或者更确切地说,将容器类型作为模板参数,因此您可以使用类似的容器,如std::unordered_map
或std::set
),它们具有锁定特定条目的功能。
包装器类必须镜像实际的std::map
类中的方法,其实现包含对锁的检查,否则只需调用底层容器类型中的方法。
如果你想修改的每个键都有一个条目,那么你应该能够在不同的线程上修改这些键的值,只要每个线程使用不同的键集,没有重叠,和只要不修改map本身的结构(即不修改map中的键集,或者以其他方式调整它的大小)。
也就是说,从技术上讲,这只适用于c++ 11。在此之前,c++假装线程不存在,并且在多线程运行时根本不保证内存模型。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何找到锁定Linux futex的C++行
- G锁定铸造到基础上会释放模拟行为
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 允许从 std::map 的密钥窃取资源?
- 如何检查线程是否锁定
- 如何在C++中找到active directory中禁用和锁定的窗口帐户
- 我应该在锁定TBitmap画布后解锁它吗
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 线程安全 std::map:锁定整个映射和单个值
- 如何使用std::lock_guard锁定对std::map的读写访问
- map是否锁定其节点以防止其他进程删除它们
- std::map中的值是否可以被锁定?