封装pthread库的几个类(2)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zeqi1991/article/details/82526051

在上一篇中,分装了MutexLock这个类,使用lock和unlock来确定临界区。
但是却没有用到最好的RTTI这个方法。下面添加一个更好的类,封装MutexLock

mutex_lock_guard.h

#ifndef __INCLUDE_MUTEX_LOCK_GUARD_H__
#define __INCLUDE_MUTEX_LOCK_GUARD_H__

#include "noncopyable.h"
class MutexLock;

class MutexLockGuard : public noncopyable
{
public:
    MutexLockGuard(MutexLock& lock);
    ~MutexLockGuard();
private:
    MutexLock& locker_;
};

#endif //__INCLUDE_MUTEX_LOCK_GUARD_H__

mutex_lock_guard.cpp

#include "mutex_lock_guard.h"
#include "mutex_lock.h"

MutexLockGuard::MutexLockGuard(MutexLock& lock) : locker_(lock)
{
    locker_.Lock();
}

MutexLockGuard::~MutexLockGuard()
{
    locker_.Unlock();
}

测试用的main.cpp

#include <iostream>
#include "mutex_lock.h"
#include "mutex_lock_guard.h"

using namespace std;

int g_number = 0;
MutexLock lock;

void* Add(void* arg)
{
    MutexLockGuard locker(lock);
    int &num = *((int*)(arg));
    for (int i = 0; i < 10000; i++)
    {
        ++num;
    }
    return NULL;
}

void* Subtraction(void* arg)
{
    MutexLockGuard locker(lock);
    int &num = *((int*)(arg));
    for (int i = 0; i < 10000; i++)
    {
        --num;
    }
    return NULL;
}

int main()
{
    pthread_t thread_pid_t1, thread_pid_t2;
    pthread_create(&thread_pid_t1, NULL, Add, &g_number);
    pthread_create(&thread_pid_t2, NULL, Subtraction, &g_number);
    pthread_join(thread_pid_t1, NULL);
    pthread_join(thread_pid_t2, NULL);
    std::cout << "g_number = " << g_number << std::endl;
    return 0;
}

makefile保持原来的文件不变
测试结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/zeqi1991/article/details/82526051
今日推荐