一、单例模式
1. 概念
- 单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享。
2. 实现思路
- 私有化该类的构造函数,以防止外界创建单例类的对象。
- 使用类的私有静态指针变量指向该类的唯一实例。
- 用一个公有的静态方法获取该实例。
3. 实现方式
- 懒汉模式:在第一次使用该对象时进行初始化。
- 饿汉模式:在程序运行时立即初始化。
4. 实现代码
(1)懒汉模式
#include <memory>
#include <mutex>
using namespace std;
class Single
{
public:
Single(Single&) = delete;
Single& operator=(const Single&) = delete;
static Single* getInstance()
{
if (ptr_ == nullptr)
{
lock_guard<mutex> locker(mutex_);
if (ptr_ == nullptr)
{
ptr_ = new Single;
}
}
return ptr_;
}
private:
~Single() {
cout << "~Single()" << endl; }
Single() {
cout << "Single()" << endl; }
static Single* ptr_;
static mutex mutex_;
};
Single* Single::ptr_ = nullptr;
mutex Single::mutex_;
class Single
{
private:
Single() {
}
~Single() {
}
public:
static Single* getinstance();
};
Single* Single::getinstance()
{
static Single obj;
return &obj;
}
(2)饿汉模式
class Single {
private:
Single() {
}
~Single() {
}
static Single* p;
public:
static Single* getinstance();
};
Single* Single::p = new Single();
Single* Single::getinstance() {
return p;
}
二、生产者-消费者模型
1. 概念
若干个生产者线程,产生任务放入到任务队列中,任务队列满了就阻塞,不满的时候就工作。
若干个消费者线程,将任务从任务队列取出处理,任务队列中有任务就工作,没有任务就阻塞。
生产者和消费者是互斥关系,两者对任务队列访问互斥。
同时生产者和消费者又是一个相互协作与同步的关系,只有生产者生产之后,消费者才能消费。
2. 示例
例:使用条件变量实现生产者和消费者模型,生产者有5个,往链表头部添加节点,消费者也有5个,删除链表头部的节点。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
struct Node
{
int number;
struct Node *next;
};
struct Node *head = NULL;
pthread_cond_t cond;
pthread_mutex_t mutex;
void *producer(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
struct Node *pnew = (struct Node *)malloc(sizeof(struct Node));
pnew->number = rand() % 1000;
pnew->next = head;
head = pnew;
printf("++++++++producer, number = %d, tid = %ld\n", pnew->number, pthread_self());
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
sleep(rand() % 3);
}
return NULL;
}
void *consumer(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
while (head == NULL)
{
pthread_cond_wait(&cond, &mutex);
}
struct Node *pnode = head;
printf("--------consumer: number: %d, tid = %ld\n", pnode->number, pthread_self());
head = pnode->next;
free(pnode);
pthread_mutex_unlock(&mutex);
sleep(rand() % 3);
}
return NULL;
}
int main()
{
pthread_cond_init(&cond, NULL);
pthread_mutex_init(&mutex, NULL);
pthread_t ptid[5];
pthread_t ctid[5];
for (int i = 0; i < 5; ++i)
{
pthread_create(&ptid[i], NULL, producer, NULL);
}
for (int i = 0; i < 5; ++i)
{
pthread_create(&ctid[i], NULL, consumer, NULL);
}