std::map中的值是否可以被锁定?

Can a value in std::map for a key be locked?

本文关键字:锁定 map std 是否      更新时间:2023-10-16

我有一个具有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_mapstd::set),它们具有锁定特定条目的功能。

包装器类必须镜像实际的std::map类中的方法,其实现包含对锁的检查,否则只需调用底层容器类型中的方法。

如果你想修改的每个键都有一个条目,那么你应该能够在不同的线程上修改这些键的值,只要每个线程使用不同的键集,没有重叠,只要不修改map本身的结构(即不修改map中的键集,或者以其他方式调整它的大小)。

也就是说,从技术上讲,这只适用于c++ 11。在此之前,c++假装线程不存在,并且在多线程运行时根本不保证内存模型。