[c++11]多线程编程(三)——竞争条件与互斥锁

竞争条件

并发代码中最多见的错误之一就是竞争条件(race condition)。而其中最多见的就是数据竞争(data race),从总体上来看,全部线程之间共享数据的问题,都是修改数据致使的,若是全部的共享数据都是只读的,就不会发生问题。可是这是不可能的,大部分共享数据都是要被修改的。ios

c++中常见的cout就是一个共享资源,若是在多个线程同时执行cout,你会发发现很奇怪的问题:c++

#include <iostream>
#include <thread>
#include <string>
using namespace std;

// 普通函数 无参
void function_1() {
    for(int i=0; i>-100; i--)
        cout << "From t1: " << i << endl;
}

int main()
{
    std::thread t1(function_1);

    for(int i=0; i<100; i++)
        cout << "From main: " << i << endl;

    t1.join();
    return 0;
}

你有很大的概率发现打印会出现相似于From t1: From main: 64这样奇怪的打印结果。cout是基于流的,会先将你要打印的内容放入缓冲区,可能刚刚一个线程刚刚放入From t1: ,另外一个线程就执行了,致使输出变乱。而c语言中的printf不会发生这个问题。编程

使用互斥元保护共享数据

解决办法就是要对cout这个共享资源进行保护。在c++中,可使用互斥锁std::mutex进行资源保护,头文件是#include <mutex>,共有两种操做:锁定(lock)解锁(unlock)。将cout从新封装成一个线程安全的函数:安全

#include <iostream>
#include <thread>
#include <string>
#include <mutex>
using namespace std;

std::mutex mu;
// 使用锁保护
void shared_print(string msg, int id) {
    mu.lock(); // 上锁
    cout << msg << id << endl;
    mu.unlock(); // 解锁
}

void function_1() {
    for(int i=0; i>-100; i--)
        shared_print(string("From t1: "), i);
}

int main()
{
    std::thread t1(function_1);

    for(int i=0; i<100; i++)
        shared_print(string("From main: "), i);

    t1.join();
    return 0;
}

修改完以后,运行能够发现打印没有问题了。可是还有一个隐藏着的问题,若是mu.lock()mu.unlock()之间的语句发生了异常,会发生什么?unlock()语句没有机会执行!致使致使mu一直处于锁着的状态,其余使用shared_print()函数的线程就会阻塞。多线程

解决这个问题也很简单,使用c++中常见的RAII技术,即获取资源即初始化(Resource Acquisition Is Initialization)技术,这是c++中管理资源的经常使用方式。简单的说就是在类的构造函数中建立资源,在析构函数中释放资源,由于就算发生了异常,c++也能保证类的析构函数可以执行。咱们不须要本身写个类包装mutexc++库已经提供了std::lock_guard类模板,使用方法以下:并发

void shared_print(string msg, int id) {
    //构造的时候帮忙上锁,析构的时候释放锁
    std::lock_guard<std::mutex> guard(mu);
    //mu.lock(); // 上锁
    cout << msg << id << endl;
    //mu.unlock(); // 解锁
}

能够实现本身的std::lock_guard,相似这样:ide

class MutexLockGuard
{
 public:
  explicit MutexLockGuard(std::mutex& mutex)
    : mutex_(mutex)
  {
    mutex_.lock();
  }

  ~MutexLockGuard()
  {
    mutex_.unlock();
  }

 private:
  std::mutex& mutex_;
};

为保护共享数据精心组织代码

上面的std::mutex互斥元是个全局变量,他是为shared_print()准备的,这个时候,咱们最好将他们绑定在一块儿,好比说,能够封装成一个类。因为cout是个全局共享的变量,无法彻底封装,就算你封装了,外面仍是可以使用cout,而且不用经过锁。下面使用文件流举例:函数

#include <iostream>
#include <thread>
#include <string>
#include <mutex>
#include <fstream>
using namespace std;

std::mutex mu;
class LogFile {
    std::mutex m_mutex;
    ofstream f;
public:
    LogFile() {
        f.open("log.txt");
    }
    ~LogFile() {
        f.close();
    }
    void shared_print(string msg, int id) {
        std::lock_guard<std::mutex> guard(mu);
        f << msg << id << endl;
    }
};

void function_1(LogFile& log) {
    for(int i=0; i>-100; i--)
        log.shared_print(string("From t1: "), i);
}

int main()
{
    LogFile log;
    std::thread t1(function_1, std::ref(log));

    for(int i=0; i<100; i++)
        log.shared_print(string("From main: "), i);

    t1.join();
    return 0;
}

上面的LogFile类封装了一个mutex和一个ofstream对象,而后shared_print函数在mutex的保护下,是线程安全的。使用的时候,先定义一个LogFile的实例log,主线程中直接使用,子线程中经过引用传递过去(也可使用单例来实现),这样就能保证资源被互斥锁保护着,外面没办法使用可是使用资源。ui

可是这个时候仍是得当心了!用互斥元保护数据并不仅是像上面那样保护每一个函数,就可以彻底的保证线程安全,若是将资源的指针或者引用不当心传递出来了,全部的保护都白费了!要记住一下两点:this

  1. 不要提供函数让用户获取资源。

    std::mutex mu;
    class LogFile {
        std::mutex m_mutex;
        ofstream f;
    public:
        LogFile() {
            f.open("log.txt");
        }
        ~LogFile() {
            f.close();
        }
        void shared_print(string msg, int id) {
            std::lock_guard<std::mutex> guard(mu);
            f << msg << id << endl;
        }
        // Never return f to the outside world
        ofstream& getStream() {
            return f;  //never do this !!!
        }
    };
  2. 不要资源传递给用户的函数。

    class LogFile {
        std::mutex m_mutex;
        ofstream f;
    public:
        LogFile() {
            f.open("log.txt");
        }
        ~LogFile() {
            f.close();
        }
        void shared_print(string msg, int id) {
            std::lock_guard<std::mutex> guard(mu);
            f << msg << id << endl;
        }
        // Never return f to the outside world
        ofstream& getStream() {
            return f;  //never do this !!!
        }
        // Never pass f as an argument to user provided function
        void process(void fun(ostream&)) {
            fun(f);
        }
    };

以上两种作法都会将资源暴露给用户,形成没必要要的安全隐患。

接口设计中也存在竞争条件

STL中的stack类是线程不安全的,因而你模仿着想写一个属于本身的线程安全的类Stack。因而,你在pushpop等操做得时候,加了互斥锁保护数据。可是在多线程环境下使用使用你的Stack类的时候,却仍然有多是线程不安全的,why?

假设你的Stack类的接口以下:

class Stack
{
public:
    Stack() {}
    void pop(); //弹出栈顶元素
    int& top(); //获取栈顶元素
    void push(int x);//将元素放入栈
private:
    vector<int> data; 
    std::mutex _mu; //保护内部数据
};

类中的每个函数都是线程安全的,可是组合起来却不是。加入栈中有9,3,8,6共4个元素,你想使用两个线程分别取出栈中的元素进行处理,以下所示:

Thread A                Thread B
int v = st.top(); // 6
                      int v = st.top(); // 6
st.pop(); //弹出6
                      st.pop(); //弹出8
                      process(v);//处理6
process(v); //处理6

能够发如今这种执行顺序下, 栈顶元素被处理了两遍,并且多弹出了一个元素8,致使`8没有被处理!这就是因为接口设计不当引发的竞争。解决办法就是将这两个接口合并为一个接口!就能够获得线程安全的栈。

class Stack
{
public:
    Stack() {}
    int& pop(); //弹出栈顶元素并返回
    void push(int x);//将元素放入栈
private:
    vector<int> data; 
    std::mutex _mu; //保护内部数据
};

//下面这样使用就不会发生问题
int v = st.pop(); // 6
process(v);

可是注意:这样修改以后是线程安全的,可是并非异常安全的,这也是为何STL中栈的出栈操做分解成了两个步骤的缘由。(为何不是异常安全的还没想明白。。)

因此,为了保护共享数据,还得好好设计接口才行。

参考

  1. C++并发编程实战
  2. C++ Threading #3: Data Race and Mutex
相关文章
相关标签/搜索