文章目录
c++设计模式
单例模式顾名思义,保证一个类仅可以有一个实例化对象,并且提供一个可以访问它的全局接口。实现单例模式必须注意一下几点:
单例类只能由一个实例化对象。
单例类必须自己提供一个实例化对象。
单例类必须提供一个可以访问唯一实例化对象的接口。
1,代码 main.cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <time.h>
#include <unistd.h>
class Controller {
private:
int m_num = 0;
std::mutex m_num_mutex;
private:
Controller(){};//private constructor
Controller(const Controller&) = delete;//clear refused to copy constructor
Controller &operator=(const Controller&) = delete;//clear refused to assignment constructor
public:
static Controller *getInstance() {
static Controller controller;
return &controller;
}
int getNum(int &num, std::string thread_name) {
//thread safety, the mutex
std::lock_guard<std::mutex> guard(m_num_mutex);
std::cout << thread_name << " get num:" << m_num << std::endl;
std::cout.flush();
num = m_num;
return 0;
};
int addNum(std::string thread_name) {
//thread safety, the mutex
std::lock_guard<std::mutex> guard(m_num_mutex);
m_num++;
std::cout << thread_name << " add num:" << m_num << std::endl;
std::cout.flush();
return 0;
};
};
class Thread {
private:
std::string m_name;
bool m_run_flag = true;
std::thread m_thread;
private:
int run() {
while(m_run_flag) {
int d_time = rand() % 5 + 1;
std::cout << "thread " << m_name << " run. delay:" << d_time << std::endl;
std::cout.flush();
Controller::getInstance()->addNum(m_name);
sleep(d_time);
int num;
Controller::getInstance()->getNum(num, m_name);
std::cout << "thread " << m_name << " run. get num:" << num << std::endl;
std::cout.flush();
}
};
public:
Thread(std::string name):m_name(name) {srand((unsigned)time(NULL));};
int createThread() {
m_run_flag = true;
m_thread = std::thread(&Thread::run, this);
m_thread.detach();
return 0;
};
int deleteThread() {
m_run_flag = false;
return 0;
};
};
int main() {
//in order to prevent multiple threads at the same time, the first call to the singleton instance.
//need before starting a thread first call all singleton instance again.
Controller::getInstance();
Thread thread_1("thread_1");
Thread thread_2("thread_2");
thread_1.createThread();
thread_2.createThread();
int count = 10;
while(count > 0) {
int num;
Controller::getInstance()->getNum(num, "main_thread");
std::cout << "main thread. get num:" << num << std::endl;
sleep(2);
count--;
}
thread_1.deleteThread();
thread_2.deleteThread();
return 0;
}
2,编译
g++ main.cpp -std=c++11 -pthread