| CODE |
class A { // this class is extend from a thread wrapper public: map <int, string> mymap; } |
| QUOTE (kasun04 @ Feb 8 2007, 03:44 AM) | ||
| I got two threads running in the same program. One thread is adding some strings to a map while the other one is reading from the same map. This can be leads to unexpected results. So I want to synchronize this thread behaviour. I'm using mutex to do so (pthread.h)
There are two methods to add to map (in main process) and read from map (in thread) . How to use mutex locks to restict the access to the map. (While we are inerting objects to the map reding from the map should be blocked) Os: Solaris POSIX Thread gcc 3.4.3 |
| CODE |
/* *You must initialise a mutex */ pthread_mutex_t myLockMutex; if (pthread_mutex_init(&myLockMutex,NULL) != 0) { std::cout << "Error on Init" << std::endl; exit(1); } /* * Then Lock a mutex: */ if (pthread_mutex_lock(&myLockMutex) != 0) { std::cout << "Error on Lock" << std::endl; exit(1); } /* * Then a release of a mutex: */ if (pthread_mutex_unlock(&myLockMutex) != 0) { std::cout << "Error on UnLock" << std::endl; exit(1); } |