C ++,如何在进程或线程之间共享数据 [英] C++, how to share data between processes or threads

查看:311
本文介绍了C ++,如何在进程或线程之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,它运行两个不同的操作,我想共享之间的变量。

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

现在,我使用线程而不是fork

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.

我尝试使用boost做:

I tried with boost doing:

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


b $ b

通过声明共享变量为volatile,但似乎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.

'd like to do is like like:

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
}

或者一个方法在线程之间轻松地共享变量?
可能是boost库可以在这种情况下有用吗?
你认为最好使用fork()吗?

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.

推荐答案

如果您可以使用 boost ,您可以使用 boost :: mutex

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
}

这篇关于C ++,如何在进程或线程之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆