C ++ how to exchange data between processes or threads

I have a program that performs two different operations, and I would like to share variables between them.

At the moment, I use threads instead of fork processes, but I am having problems exchanging variables, even if I declare them unstable.

I tried using boost:

boost::thread collisions_thread2(boost::bind(function_thread2);

declaring the shared variables as volatile, but it seems the function_thread2 () function cannot see the changes in the shared variables.

What I would like to do is something like:

thread1:

while(true){
//..do somet stuff
check variable1
}

thread2:

while(true){
do some other stuff
check and write on variable1
}

Can you offer me a tutorial or method to easily exchange variables between threads? Maybe in this case the acceleration library can be useful? What do you think is best to use fork ()?

, , , .

+5
3

boost, boost::mutex.

// mtx should be shared for all of threads.
boost::mutex mtx;

// code below for each thread
{
  boost::mutex::scoped_lock lk(mtx);
  // do something
}
+2

posix ( ), pthread_mutex_t.

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

, :

pthread_mutex_lock(&lock);
//access the data
pthread_mutex_unlock(&lock);
+2

Any kind of mutex lock or unlock will work. Regarding your question on volatility, this keyword is good practice, especially in multi-threaded programs like yours. But this does not affect the way the lock and unlock. volatile just tells the compiler not to optimize the variable, for example. by placing it in the registry. Here is a very good explanation:

http://drdobbs.com/cpp/184403766

+1
source

All Articles