shared_ptr:多线程对共享申请资源的访问和回收

利用shared_ptr的共享引用计数、引用结束资源系统回收的机制,实现多线程对共享申请资源的访问和回收。

#include <vector>
#include <memory>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;

class Student
{
    public:
        Student()
        {

        }

        ~Student()
        {
            std::cout << "Student Destructor" << std::endl;
        }

    public:
        size_t number;
};

std::shared_ptr<Student> g_object;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;

class Mutex
{
    public:
        Mutex(pthread_mutex_t mutex) : own_mutex(mutex)
        {
            pthread_mutex_lock(&own_mutex);
            std::cout << "mutex lock id" << pthread_self() << std::endl;
        }

        ~Mutex()
        {
            pthread_mutex_unlock(&own_mutex);
            std::cout << "mutex unlock id" << pthread_self() << std::endl;
        }

    public:
        pthread_mutex_t own_mutex;
};

class Test
{
    public:
        static void* Change(void* pData)
        {
            while (true)
            {
                {
                    Mutex temp_mutex(g_mutex);
                    std::shared_ptr<Student> temp_module(new Student());
                    g_object = temp_module;
                    g_object->number = random();
                    std::cout << "change thread id = " << pthread_self() << " number = " << g_object->number << std::endl;
                }
                sleep(1);
            }
        }

        static void* Display(void* pData)
        {
            while (true)
            {
                {
                    Mutex temp_mutex(g_mutex);
                    if (NULL == g_object)
                    {
                        std::cout << "work thread id = " << pthread_self() << " g_obj is null" << std::endl;
                    }
                    else
                    {
                        std::shared_ptr<Student> temp_module = g_object;
                        std::cout << "work thread id = " << pthread_self() << " number = " << (*temp_module).number << std::endl;
                    }
                }
                sleep(2.3);
            }
        }
};

int main()
{
    pthread_t tid;
    std::vector<pthread_t> tid_vec;

    pthread_create(&tid, NULL, Test::Change, NULL);
    std::cout << "change thread id = " << tid << std::endl;
    tid_vec.push_back(tid);

    for (int uli = 0; uli < 2; ++uli)
    {
        pthread_create(&tid, NULL, Test::Display, NULL);
        std::cout << "work thread id = " << tid << std::endl;
        tid_vec.push_back(tid);
    }

    for (auto iter = tid_vec.begin(); iter != tid_vec.end(); ++iter)
    {
        pthread_join(*iter, NULL);
    }

    return 0;
}

//g++ -oxx -pthread tqy.cpp --std=c++11

猜你喜欢

转载自tqywork.iteye.com/blog/2244861