添加线程池

master
zcy 2021-03-10 17:48:03 +08:00
parent 5854d9bcc4
commit 403f17a599
7 changed files with 104 additions and 5 deletions

View File

@ -50,6 +50,8 @@
"xstring": "cpp",
"xtr1common": "cpp",
"xutility": "cpp",
"ctime": "cpp"
"ctime": "cpp",
"threadpool.h": "c",
"*.rh": "cpp"
}
}

View File

@ -2,12 +2,12 @@
using namespace std;
#include<stdio.h>
#include "thread_usage.h"
#include "threadpool.h"
int main(){
std::cout<<"test start"<<endl;
// TestPromiseFutureBefore();
try{
TestThreadDetch();
TestConditionVariable();
}catch( std::exception e){
std::cout<<"exception"<<e.what();
}

View File

@ -29,7 +29,7 @@ void independentThread()
std::cout << "Exiting concurrent thread.\n";
}
void TestThreadDetch()
void TestThreadDetach()
{
std::cout << "Starting thread caller.\n";
std::thread t(independentThread);
@ -38,4 +38,61 @@ void TestThreadDetch()
std::cout << "Exiting thread caller.\n";
std::cout << "done.\n";
}
std::mutex gMtx;
void print_even (int x) {
if (x%2==0) std::cout << x << " is even\n";
else throw (std::logic_error("not even"));
}
void print_thread_id (int id) {
try {
// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
std::lock_guard<std::mutex> lck (gMtx);
print_even(id);
}
catch (std::logic_error& e ) {
std::cout << "[exception caught]: ";
std::cout<< e.what()<<std::endl;
}
}
void TestLockGuard(){
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_thread_id,i+1);
for (auto& th : threads) th.join();
return ;
}
std::mutex cMtx; // 全局互斥锁.
std::condition_variable gCv; // 全局条件变量.
bool gReady = false; // 全局标志位.
void do_print_id(int id){
std::unique_lock <std::mutex> lck(cMtx);
while (!gReady) // 如果标志位不为 true, 则等待...
gCv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,
// 线程被唤醒, 继续往下执行打印线程编号id.
std::cout << "thread " << id << '\n';
}
void go(){
std::unique_lock <std::mutex> lck(cMtx);
gReady = true; // 设置全局标志位为 true.
gCv.notify_one(); // 唤醒所有线程.
}
int TestConditionVariable() {
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(do_print_id, i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto & th:threads)
th.join();
return 0;
}

View File

@ -8,4 +8,6 @@
#include <cstdlib>
void TestPromiseFutureBefore();
void TestThreadDetch();
void TestThreadDetach();
void TestLockGuard();
int TestConditionVariable();

View File

@ -0,0 +1,18 @@
#include "threadpool.h"
int ThreadPool::AddTask(){
}
void ThreadPool::Start(){
}
void ThreadPool::Stop(){
for (auto & th:threads)
th.join();
}
bool ThreadPool::Started(){
}

View File

@ -0,0 +1 @@
#include "threadpool.h"

View File

@ -0,0 +1,19 @@
#pragma once
#include <thread>
#include <mutex>
#include <atomic>
#include <vector>
using namespace std;
typedef class CThreadPool {
public:
CThreadPool(int num);
int AddTask();
void Start();
void Stop();
bool Started();
private:
bool mStarted;
std::vector<std::thread> mThreads;
}ThreadPool;