开发者

C++ Threads and Simple blocking mechanism?

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 o开发者_运维技巧bject

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.


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
}; 


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


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 );
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜