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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 11:28:33

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
}

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

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

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