C++, how to share data between processes or threads

╄→尐↘猪︶ㄣ 提交于 2019-12-10 04:52:51

问题


I have a program which runs two different operations and i'd like to share variables between them.

At the moment, i'm using threads instead of fork processes but i'm having problems in sharing variables even if I declared them as volatile.

I tried with boost doing:

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

by declaring the shared variables as volatile, but it seems that function_thread2() function is not able to see changes on the shared variables.

What i'd 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 suggest me a tutorial or a method to easily share variable between threads? May be boost library can be useful in this case? Do you think it's better to use fork()?

I know that i have to use mutex in order to avoid critical situations, but i never used it.


回答1:


If you can use boost, you can use 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:


If using the posix threading libs (which I recommend) then use pthread_mutex_t.

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

Then, in each thread when you want to synchronize data access:

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



回答3:


any kind of mutex lock or unlock would work. As far as your question on volatile goes, this keyword is a good practice especially in multi-threaded programs such as yours. But it doesn't affect the way you lock and unlock. volatile simply tells the compiler not to optimize a variable for e.g. by putting it in a register. Here's a very good explanation:

http://drdobbs.com/cpp/184403766



来源:https://stackoverflow.com/questions/9505131/c-how-to-share-data-between-processes-or-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!