Linux 【线程池】【单例模式】【读者写者问题】
在Linux环境下,使用线程池和单例模式来解决读者写者问题的示例代码如下:
#include <pthread.h>
#include <stdio.h>
// 线程安全的计数器
int counter = 0;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
// 读写锁
pthread_rwlock_t rwlock;
// 初始化读写锁
void init_rwlock() {
pthread_rwlock_init(&rwlock, NULL);
}
// 读者上锁
void read_lock() {
pthread_rwlock_rdlock(&rwlock);
}
// 读者解锁
void read_unlock() {
pthread_rwlock_unlock(&rwlock);
}
// 写者上锁
void write_lock() {
pthread_rwlock_wrlock(&rwlock);
}
// 写者解锁
void write_unlock() {
pthread_rwlock_unlock(&rwlock);
}
// 任务函数:写者任务
void writer_task() {
write_lock();
// 模拟写操作
printf("Writer: Performing write operation...\n");
sleep(1); // 模拟耗时操作
printf("Writer: Write operation completed.\n");
write_unlock();
}
// 任务函数:读者任务
void reader_task() {
read_lock();
// 模拟读操作
printf("Reader: Performing read operation...\n");
sleep(1); // 模拟耗时操作
printf("Reader: Read operation completed.\n");
read_unlock();
}
// 线程入口函数
void* thread_entry(void* arg) {
int task_type = *(int*)arg;
switch (task_type) {
case 0:
writer_task();
break;
case 1:
reader_task();
break;
}
return NULL;
}
// 线程池类
class ThreadPool {
public:
ThreadPool(int size) {
pool_size = size;
threads = new pthread_t[pool_size];
queue = new int[pool_size]; // 使用一个简单的队列模拟任务队列
for (int i = 0; i < pool_size; ++i) {
queue[i] = -1; // 初始化任务队列为空
}
}
~ThreadPool() {
delete[] threads;
delete[] queue;
}
void start() {
for (int i = 0; i < pool_size; ++i) {
pthread_create(&threads[i], NULL, &thread_entry, &queue[i]);
}
}
void add_task(int task_type) {
for (int i = 0; i < pool_size; ++i) {
if (queue[i] == -1) {
queue[i] = task_type;
break;
}
}
}
private:
int pool_size;
pthread_t* threads;
int* queue;
};
// 单例模式的线程池
class ThreadPoolSingleton {
public:
static ThreadPoolSingleton& get_instance() {
static ThreadPoolSingleton instance;
return instance;
}
void start_pool() {
pool.start();
}
void add_writer_task() {
pool.add_
评论已关闭