multithreading - In C++, is there a way to lock the object itself? -
i have stl map synchronized across several threads. have...
function (modifies map)
void modify(std::string value) { pthread_mutex_lock(&map_mutex); my_map[value] = value; pthread_mutex_unlock(&map_mutex); } function b (reads map)
std::string read(std::string key) { std::string value; pthread_mutex_lock(&map_mutex); std::map<std::string, std::string>::iterator = my_map.find(key); pthread_mutex_unlock(&map_mutex); if(it != my_map.end()) { return it->second; } else { return "dne"; } } this synchronized across threads, due mutex. however, have lock mutex in function b though not modifying map @ all. there way lock my_map object in function a, , not lock in function b while keeping thread synchronization. way, instances/calls of function b continue run freely, long function not being run?
thanks
you don't want lock container, want lock accesses container i.e. iterators or pointers it. need move accesses locked region of code.
std::string read(std::string key) { std::string value = "dne"; pthread_mutex_lock(&map_mutex); std::map<std::string, std::string>::iterator = my_map.find(key); if(it != my_map.end()) { value = it->second; } pthread_mutex_unlock(&map_mutex); return value; } there's no practical way inside object itself.
Comments
Post a Comment