为了保证退出程序前,所有运行的线程都已经停止。我引入了信号量,对线程池进行改造。改造实现代码如下。
#pragma once
#include<queue>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<iostream>
#include"Semaphore.h"
using namespace std;
class Thread
{
public:
typedef void(*TheadFuncion)();
thread* th = nullptr;
void* data;
TheadFuncion func;
bool exit = false;
bool isThreadEnd = false;
bool idle = true;
Semaphore taskSemaphore;
Semaphore quitSemaphore;
void Func()
{
isThreadEnd = false;
while (!exit) {
this->func();
idle = true;
taskSemaphore.wait();
}
isThreadEnd = true;
quitSemaphore.signal();
}
bool Start(Thread::TheadFuncion func)
{
if (!idle) {
return false;
}
idle = false;
this->func = func;
if (nullptr == th) {
th = new thread([&]() {
Func();
});
th->detach();
}
else {
taskSemaphore.signal();
}
return true;
}
bool IsIdle() {
return idle;
}
void Stop()
{
exit = true;
if (!isThreadEnd) {
taskSemaphore.signal();
quitSemaphore.wait();
}
delete th;
}
Thread(){
}
~Thread(){
if (nullptr == th) {
exit = true;
}else {
if (!exit) {
Stop();
}
}
}
};
class ThreadPool
{
public:
vector<Thread*> threads;
typedef std::vector<Thread*>::iterator Iterator;
mutex mtx;
bool isEnd = false;
public:
ThreadPool(int threadCount)
{
for (int i = 0; i < threadCount; i++) {
Thread* thread = new Thread();
threads.push_back(thread);
}
}
~ThreadPool() {
Iterator iter = threads.begin();
while (iter != threads.end()) {
if (nullptr != *iter) {
delete *iter;
iter = threads.erase(iter);
}
else {
iter++;
}
}
isEnd = true;
}
bool Add(Thread::TheadFuncion func) {
mtx.lock();
Iterator iter = threads.begin();
bool isAddOk = false;
while (iter != threads.end()) {
if ((*iter)->IsIdle()) {
isAddOk = (*iter)->Start(func);
if (!isAddOk) {
iter++;
}
else {
break;
}
}
else {
iter++;
}
}
mtx.unlock();
return isAddOk;
}
}; 信号量实现代码如下:
#include <mutex>
#include <condition_variable>
#include<iostream>
using namespace std;
class Semaphore {
private:
int count;
int wakeups;
std::mutex mutex;
std::condition_variable condition;
public:
Semaphore(int value = 0) :count(value), wakeups(0) {}
void wait() {
std::unique_lock<std::mutex> lock(mutex);
if (--count < 0) {
condition.wait(lock, [&]()->bool {return wakeups > 0; });
--wakeups;
}
}
void signal() {
std::lock_guard<std::mutex> lock(mutex);
if (++count <= 0) {
++wakeups;
condition.notify_one();
}
}
};信号量代码引用链接:
http://www.360doc.com/content/15/0303/20/203028_452313531.shtml
本文介绍了一种使用信号量改进线程池的方法,确保程序退出时所有线程均已停止。通过信号量控制线程的启动和停止,并提供线程池及线程类的具体实现代码。
799

被折叠的 条评论
为什么被折叠?



