Thread(線程工具)
ll/api/thread/ · 通用
概述
Thread 模塊提供了線程池執行器、服務器線程執行器和用於併發編程的同步工具。
頭文件
| 頭文件 | 說明 |
|---|---|
ll/api/thread/ThreadPoolExecutor.h | 線程池執行器 |
ll/api/thread/ServerThreadExecutor.h | 服務器主線程執行器 |
ll/api/thread/GlobalThreadPauser.h | 暫停所有遊戲線程 |
ll/api/thread/ThreadName.h | 線程命名工具 |
核心類
ThreadPoolExecutor
C++
namespace ll::thread {
class ThreadPoolExecutor : public coro::Executor {
public:
explicit ThreadPoolExecutor(std::string name, size_t nThreads = 1);
void resize(size_t nThreads);
void destroy();
void execute(std::function<void()>) const override;
std::shared_ptr<data::CancellableCallback> executeAfter(std::function<void()>, Duration) const override;
static ThreadPoolExecutor const& getDefault();
};
}ServerThreadExecutor
C++
namespace ll::thread {
class ServerThreadExecutor : public coro::Executor {
public:
ServerThreadExecutor(std::string name, Duration maxOnceDuration, size_t checkPack);
void execute(std::function<void()>) const override;
std::shared_ptr<data::CancellableCallback> executeAfter(std::function<void()>, Duration) const override;
static ServerThreadExecutor const& getDefault();
};
}使用方法
線程池執行
C++
#include "ll/api/thread/ThreadPoolExecutor.h"
void runInBackground() {
auto& executor = ll::thread::ThreadPoolExecutor::getDefault();
executor.execute([] {
// 在后台线程中运行
});
}服務器線程執行
C++
#include "ll/api/thread/ServerThreadExecutor.h"
void runOnServerThread() {
auto& executor = ll::thread::ServerThreadExecutor::getDefault();
executor.execute([] {
// 在服务器主线程中运行
// 在此处访问游戏状态是安全的
});
}延遲執行
C++
#include "ll/api/thread/ThreadPoolExecutor.h"
#include <chrono>
void scheduleTask() {
auto& executor = ll::thread::ThreadPoolExecutor::getDefault();
auto callback = executor.executeAfter(
[] {
// 5 秒后运行
},
std::chrono::seconds(5)
);
// 可以取消回调
// callback->cancel();
}自定義線程池
C++
#include "ll/api/thread/ThreadPoolExecutor.h"
void createCustomPool() {
ll::thread::ThreadPoolExecutor myPool("MyPool", 4); // 4 个线程
myPool.execute([] {
// 工作
});
myPool.resize(8); // 调整为 8 个线程
}相關模塊
- Coroutine(協程) — 協程使用執行器
- Chrono(遊戲時間) — 延遲執行的時長類型