线程 c++防止价值改变
我使用 boosthread 创建 3 个线程,每次调用相同的函数并传递不同的参数。 例如 1/ thread.add(function, int a1, std::string b), thread.add(function, int a2, std::string b), thread.add(function, int a3, std::string b), thread.add(function, int a4, std::string b)
当线程内的全局值更改时,我不希望其他线程执行 并再次更改该值 例如 function(a,b){
if(该线程发生了某些事情) value = 5;
//如果什么也没发生 值=1; ?
如果一个线程获得值 5,那么我不希望其他线程干扰该值并使其返回到 1。我该如何执行此操作 谢谢。
也许做到这一点的方法是使用 boost:mutex 但我没有看到这样做有任何好处,因为这个值只是找到的 在 return 语句之前,我很可能使用了 boost join_all()。但这会降低效率。
I am using boosthread to create 3 threads calling the same function each time with different arguments being passed.
E.g. 1/ thread.add(function, int a1, std::string b), thread.add(function, int a2, std::string b),
thread.add(function, int a3, std::string b), thread.add(function, int a4, std::string b)
When a global value within the thread is changed I do not want the other threads to execute
and change the value again
E.g function(a,b){
if(something happened for that thread) value = 5;
//if nothing happened
value = 1;
}
If one thread gets a value of 5 then I do not want the other threads to interfere with that value and make it go back to 1. How can I do this? Thanks.
Maybe the way to do this is to use boost:mutex but I do not see any gain in doing so because this value is found just
before the return statement and I might well have used boost join_all(). But this would be less efficient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我有一个例子可以帮助你。
它使用 C++11,但可以轻松转换为 Boost。
该算法很简单,它由两个主要部分组成:
每个线程的作用:
初始化一个变量, 初始化器功能有效。
1.使用互斥锁来防止对共享变量的多次访问(保证该函数一次只能由一个线程访问)
2.如果变量尚未初始化,则使用线程名称对其进行初始化,并将布尔值设置为 true(变量已初始化)
3.否则什么也不做
希望有帮助,如果没有回答问题请随时告诉我
I have one example that will help you.
It uses C++11 but can be transposed to Boost easily.
the algorithm is simple, it is made of two main parts:
What each thread does:
How does the unique intializer function works.
1.uses a mutex to prevent multiple access to shared variables (guarantees that ths function is only acceesed by one thread at a time)
2.If the variables has not been initialized it initializes it with the name of the thread and sets the boolean to true (variable initialized)
3. otherwise does nothing
Hope that helps, feel free to tell me if does not answer the question