views:

95

answers:

4

I have a program in C++ that runs a bunch of threads to manipulate the same data. Each of these threads have a pointer to an object that is being manipulated, for example:

thread1 and thread2 both have a pointer to object1
object1->addSomething() can be used by either thread1 or 2 and refer to the same object

Now, these operations might give some trouble if they are being done at the same moment by both threads, so I want a simple mechanism for blocking. What I want is simply this:

void method()
{
  waitUntilFree()
  blockForOthers()
  doSomething()
  unblock()
}

Is there a simple way to do this? I just want to block and wait until it is free. I don't mind that the thread might have to wait a while. Is there an easy mechanism to do this? I use Boost for these threads but I couldn't for the life of me figure out a way to do this (seemlingly) simple block-and-wait thing.

+1  A: 

Use mutex.

More information about it you can find at http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#SYNCHRONIZATION

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int  counter = 0;

main()
{
   int rc1, rc2;
   pthread_t thread1, thread2;

   /* Create independent threads each of which will execute functionC */

   if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )
   {
      printf("Thread creation failed: %d\n", rc1);
   }

   if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )
   {
      printf("Thread creation failed: %d\n", rc2);
   }

   /* Wait till threads are complete before main continues. Unless we  */
   /* wait we run the risk of executing an exit which will terminate   */
   /* the process and all threads before the threads have completed.   */

   pthread_join( thread1, NULL);
   pthread_join( thread2, NULL); 

   exit(0);
}

void *functionC()
{
   pthread_mutex_lock( &mutex1 );
   counter++;
   printf("Counter value: %d\n",counter);
   pthread_mutex_unlock( &mutex1 );
}
Svisstack
That's C rather than C++ (it's int main() in C++), but a nice little example for the POSIX API. Perhaps somebody should mention that mutex stands for mutual exclusion, any one thread holding the lock excludes others from acquiring it....
Tony
+2  A: 

Since you're already using Boost, you can use a Boost mutex to protect simultaneous access by multiple threads.

Then use a join() on each thread to wait for it to complete.

// create the mutex where it can be accessed by all threads
boost::mutex lock;

// in each thread
lock.lock();
// do something with shared data
lock.unlock();

// for each thread
thread.join(); // wait for thread to finish
Ferruccio
Why join if exclusive access is desired? In that case a simple RAII-style [`mutex::scoped_lock`](http://www.boost.org/doc/libs/1_44_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.mutex) is much better suited.
Georg Fritzsche
I'm agree with Ferruccio
Davit Siradeghyan
@Georg Fritzsche - agreed. scoped_lock is better. I just wanted to keep the example simple. As for the join, I guess it's just a practice I've fallen into, always waiting for threads to finish.
Ferruccio
As Georg says, a scoped lock is better as it ensures you don't forget to unlock and handles exceptions. Your explanation is generally good though - great that it addresses the boost library being used - but your mention of join is a bit confusing as you make it look like lock creation, usage and join are a sequence. Introducing distinct clear sections for a main thread creating other threads, data processing using mutex, and the main thread then joining the others, would read better.
Tony
A: 

You are looking for so-called mutexes. These come as part of the thread library. Have a look at this dr. dobbs article.

Adrian Grigore
+5  A: 

As noted by Ferruccio you can use a Mutex like Boost.Mutex from the same library for synchronization:

class X {
    boost::mutex m_mutex;
public:
    void method() {
        boost::mutex::scoped_lock lock(m_mutex);
        // ... now locked, do stuff
    } // mutex automatically unlocked when scoped_lock is destructed
}; 
Georg Fritzsche