View Full Version: Thread Scnchronization

C++ Learning Community > C++ Help > Thread Scnchronization


Title: Thread Scnchronization


kasun04 - February 8, 2007 08:44 AM (GMT)
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)

CODE

class A {
      // this class is extend from a thread wrapper
      public: map <int, string> mymap;
}


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

myork - February 8, 2007 02:21 PM (GMT)
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)

CODE

class A {
      // this class is extend from a thread wrapper
      public: map <int, string> mymap;
}


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


Thats simple enough.

The things you need are:
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);
}


I leave it as an exercise on how to add this to your class (as I don't do homework).

PS. Why does class A need to derive from a Thread wrapper?

PPS: Since this is C++ you should probably put the Lock/Unlock in a separate class so that everything is exception safe. But that is something we can go over latter when you have the basics.




Hosted for free by InvisionFree