我有一個簡單的std :: map鍵值。我希望這個地圖是線程安全的。我不想鎖定整個地圖。由於我的線程只能處理(更新,刪除)地圖上特定鍵的值,所以我不想鎖定整個地圖。我希望其他線程能夠在地圖上工作,當然不是鎖定的值。可以鎖定某個鍵的std :: 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;
}
}
順便說一句,在*句子標誌之前放置空格*是不好的做法。就這樣你知道將來的機器着作。 – 2013-02-28 09:46:02
@ChristianRau我會照顧的 – 2013-03-01 07:45:37