我应该使用互斥量保护基本类型上的操作,以确保C ++中的线程安全吗? [英] Should I protect operations on primitive types with mutexes for being thread-safe in C++?

查看:69
本文介绍了我应该使用互斥量保护基本类型上的操作,以确保C ++中的线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于相当简单的操作,实现线程安全的最佳方法是什么?

What is the best approach to achieve thread-safety for rather simple operations?

考虑一对功能:

void setVal(int val)
{
    this->_val = val;
}

int getVal() {
     return this->_val;
}

由于甚至不能保证原始类型的分配都是原子的,因此我应该以以下方式将程序中的每个getter和setter修改为线程安全的吗?

Since even assignments of primitive types aren't guaranteed to be atomic, should I modify every getter and setter in the program in the following way to be thread-safe?

void setVal(int val)
{
    this->_mutex.lock();
    this->_val = val;
    this->_mutex.unlock();
}

int getVal() {
     this->_mutex.lock();
     int result = this->_val;
     this->_mutex.unlock();
     return result;
}

推荐答案

您是否在多个线程中使用_val?如果不是,则为否,您无需同步对其的访问.

Are you using _val in multiple threads? If not, then no, you don't need to synchronize access to it.

如果在多个线程中使用它,那么是的,您需要使用互斥锁或原子类型(例如C ++ 0x中的std::atomic<T>)同步访问,尽管其他线程库具有非标准原子类型,例如好).

If it is used from multiple threads, then yes, you need to synchronize access, either using a mutex or by using an atomic type (like std::atomic<T> in C++0x, though other threading libraries have nonstandard atomic types as well).

这篇关于我应该使用互斥量保护基本类型上的操作,以确保C ++中的线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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