单个变量的线程安全

编程入门 行业动态 更新时间:2024-10-27 23:20:10
本文介绍了单个变量的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我了解线程安全性的概念.我正在寻求建议,以在尝试保护单个变量时简化线程安全性.

I understand the concept of thread safety. I am looking for advice to simplify thread safety when trying to protect a single variable.

说我有一个变量:

double aPass;

并且我想保护此变量,所以我创建了一个互斥锁:

and I want to protect this variable, so i create a mutex:

pthread_mutex_t aPass_lock;

现在我可以想到两种好的方法,但是它们都有令人讨厌的缺点.首先是使线程安全类保存该变量:

Now there are two good ways i can think of doing this but they both have annoying disadvantages. The first is to make a thread safe class to hold the variable:

class aPass { public: aPass() { pthread_mutex_init(&aPass_lock, NULL); aPass_ = 0; } void get(double & setMe) { pthread_mutex_lock(aPass_lock); setMe = aPass_ pthread_mutex_unlock(aPass_lock); } void set(const double setThis) { pthread_mutex_lock(aPass_lock); aPass_ = setThis; pthread_mutex_unlock(aPass_lock); } private: double aPass_; pthread_mutex_t aPass_lock; };

现在,这将完全确保aPass的安全,没有任何错误可以触摸,是的!但是,请查看所有混乱情况并想象访问它时的混乱情况.毛.

Now this will keep aPass totally safe, nothing can be mistaken and ever touch it, YAY! however look at all that mess and imagine the confusion when accessing it. gross.

另一种方法是使它们都可访问,并确保在使用aPass之前锁定互斥锁.

The other way is to have them both accessible and to make sure you lock the mutex before you use aPass.

pthread_mutex_lock(aPass_lock); do something with aPass pthread_mutex_unlock(aPass_lock);

但是,如果有人加入该项目该怎么办,如果您忘记一次锁定该项目怎么办.我不喜欢调试很难解决的线程问题.

But what if someone new comes on the project, what if you forget one time to lock it. I don't like debugging thread problems they are hard.

有没有一种好方法(使用pthreads,因为我必须使用几乎没有boost支持的QNX)锁定单个变量而不需要一个大类,并且比创建一个互斥锁更安全吗?

Is there a good way to (using pthreads because i have to use QNX which has little boost support) To lock single variables without needing a big class and that is safer then just creating a mutex lock to go with it?

推荐答案

std::atomic<double> aPass;

前提是您拥有C ++ 11.

provided you have C++11.

更多推荐

单个变量的线程安全

本文发布于:2023-08-04 23:03:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1300369.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!