单个变量的线程安全 [英] Thread Safety Of a single variable

查看:56
本文介绍了单个变量的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于单个变量的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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