在访问具有多个线程的类成员时,如何确保线程安全

时间:2016-07-13 14:02:18

标签: c++ multithreading thread-safety boost-mutex

我正在尝试让线程同步工作。 以下是示例代码(Runnable C++ shell example)以供说明。 运行程序时,将执行三个成员函数bar1()bar2()bar3()。 我的目标是为每个函数使用一个线程。 我可以在我的开发环境中访问boost库。 我知道如何使用线程,并在下面实现了ThreadedProcess()函数。但是我理解它并不是线程安全的,因为多个线程可能想要同时访问同一个内存。 所以我的问题是,我如何确保成员一次只能被一个线程访问。 谢谢!

#include <iostream>
#include <string>




   struct TestStruct {
        int nVal;
        double dVal;
        TestStruct(){}
        TestStruct(int n, double d) : nVal(n), dVal(d)
        {
        }
    };

    class Foo{

    public:

        Foo() :m_oO1(58, 17.3), m_oO2(11, 20.8), m_oO3(7, 56.3) {}

        ~Foo(){}

        void Process()
        {
            bar1();
            bar2();
            bar3();
        }

        void ThreadedProcess()
        {

            m_oThread1 = boost::thread(boost::bind(&Foo::bar1, this));
            m_oThread2 = boost::thread(boost::bind(&Foo::bar2, this));
            m_oThread3 = boost::thread(boost::bind(&Foo::bar3, this));
        }

    protected:

        TestStruct m_oO1;
        TestStruct m_oO2;
        TestStruct m_oO3;
        TestStruct m_oO4;

        boost::thread m_oThread1;
        boost::thread m_oThread2;
        boost::thread m_oThread3;

        int bar1()
        {
            int nRet = m_oO1.nVal * m_oO2.nVal;
            std::cout << nRet << std::endl;
            return nRet;
        }

        double bar2()
        {
            double dRet = m_oO2.dVal + m_oO3.dVal;
            std::cout << dRet << std::endl;
            return dRet;
        }

        double bar3()
        {
            double dRet = m_oO2.dVal * m_oO3.dVal * m_oO3.dVal;
            std::cout << dRet << std::endl;
            return dRet;
        }

    };

    int main(int /*argc*/, char** /*argv*/)
    {
        Foo myFoo;
        myFoo.Process();
        myFoo.ThreadedProcess();
    }

0 个答案:

没有答案