115 lines
2.9 KiB
C++
115 lines
2.9 KiB
C++
#include <iostream>
|
|
#include <random>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <thread>
|
|
#include <vector>
|
|
#include <mutex>
|
|
|
|
#ifdef _WIN32
|
|
#include <windows.h>
|
|
#endif
|
|
|
|
#include "IVrThreadPool.h"
|
|
|
|
// ============================================================================
|
|
// 简单测试:固定线程数 + 随机等待时间,打印线程执行顺序
|
|
// ============================================================================
|
|
|
|
std::mutex m_shareData;
|
|
|
|
void ShareData(bool bStart, int index, int sleepMs)
|
|
{
|
|
std::lock_guard<std::mutex> lck(m_shareData);
|
|
|
|
if (bStart) {
|
|
std::cout << "[tesk] [" << index << "] start, sleep=" << sleepMs << "ms" << std::endl;
|
|
}
|
|
else {
|
|
std::cout << "[tesk] [" << index << "] end" << std::endl;
|
|
}
|
|
|
|
}
|
|
|
|
void ExecFunc(void* pParam)
|
|
{
|
|
auto* pIndex = static_cast<int*>(pParam);
|
|
|
|
// 随机等待 100~2000ms
|
|
thread_local std::mt19937 gen(std::random_device{}());
|
|
std::uniform_int_distribution<int> dist(10, 200);
|
|
int sleepMs = dist(gen);
|
|
|
|
ShareData(true, *pIndex, sleepMs);
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(sleepMs));
|
|
|
|
ShareData(false, *pIndex, sleepMs);
|
|
}
|
|
|
|
int TestThreadPool(unsigned int count)
|
|
{
|
|
const int kMaxThreads = 4;
|
|
const int kTaskCount = 10;
|
|
|
|
std::cout << "======================"<< count << "============================" << std::endl;
|
|
std::cout << " ThreadPool demo (threads=" << kMaxThreads << ", tasks=" << kTaskCount << ")" << std::endl;
|
|
std::cout << "=================================================================" << std::endl;
|
|
|
|
// 准备参数(每个任务一个索引号)
|
|
std::vector<int> taskParams;
|
|
for (int i = 0; i < kTaskCount; ++i)
|
|
{
|
|
taskParams.push_back(i + 1);
|
|
}
|
|
|
|
// ── 1. 创建线程池 ──
|
|
IVrThreadPool* pPool = nullptr;
|
|
if (!IVrThreadPool::CreateThreadPool(&pPool, kMaxThreads))
|
|
{
|
|
std::cerr << "[FAIL] CreateThreadPool" << std::endl;
|
|
return -1;
|
|
}
|
|
|
|
// ── 2. 提交任务 ──
|
|
for (int i = 0; i < kTaskCount; ++i)
|
|
{
|
|
int ret = pPool->ExecTask(ExecFunc, &taskParams[i]);
|
|
if (ret != VrThreadPoolError::Ok)
|
|
{
|
|
std::cerr << "[FAIL] ExecTask(" << i << ") ret=" << ret << std::endl;
|
|
delete pPool;
|
|
return -2;
|
|
}
|
|
}
|
|
|
|
// ── 3. 等待所有任务完成 ──
|
|
std::cout << "waiting for " << kTaskCount << " tasks..." << std::endl;
|
|
|
|
bool finished = pPool->WaitAllTaskFinish();
|
|
if (!finished)
|
|
{
|
|
std::cerr << "[FAIL] WaitAllTaskFinish timeout" << std::endl;
|
|
delete pPool;
|
|
return -3;
|
|
}
|
|
|
|
std::cout << "all tasks done!" << std::endl;
|
|
|
|
// ── 4. 销毁 ──
|
|
delete pPool;
|
|
return 0;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
#ifdef _WIN32
|
|
SetConsoleOutputCP(CP_UTF8);
|
|
#endif
|
|
unsigned int index = 0;
|
|
while (true) {
|
|
TestThreadPool(++index);
|
|
}
|
|
|
|
return 0;
|
|
}
|