採用 共享旗標 + 條件變量 模式,避免直接操作執行緒(如 SuspendThread)導致死鎖或資源洩漏。
struct TaskContext {
std::mutex mtx;
std::condition_variable cv;
bool paused = false;
bool cancelled = false;
// 計算所需的中間狀態(數組指針、進度索引等)
int* array;
size_t progress;
};
void worker(TaskContext& ctx) {
for (size_t i = ctx.progress; i < N; ++i) {
std::unique_lock<std::mutex> lk(ctx.mtx);
ctx.cv.wait(lk, [&]{ return !ctx.paused || ctx.cancelled; });
if (ctx.cancelled) break;
// 執行單步計算
heavy_computation(ctx.array[i]);
ctx.progress = i + 1; // 關鍵:持久化進度
}
}
void pause(TaskContext& ctx) {
std::lock_guard<std::mutex> lk(ctx.mtx);
ctx.paused = true;
}
void resume(TaskContext& ctx) {
std::lock_guard<std::mutex> lk(ctx.mtx);
ctx.paused = false;
ctx.cv.notify_one();
}
void cancel(TaskContext& ctx) {
std::lock_guard<std::mutex> lk(ctx.mtx);
ctx.cancelled = true;
ctx.cv.notify_all();
}
TaskContext 序列化至檔案(JSON/Protobuf),包含 progress、array 等關鍵狀態。progress 傳入新建立的 TaskContext,工作執行緒自動從中斷點繼續。std::mutex/condition_variable,僅存儲業務狀態。| 方案 | 優點 | 缺點 |
|---|---|---|
| 旗標+條件變量 | 安全、可移植、精確控制 | 需修改計算迴圈插入檢查點 |
| 寫檔案检查點 | 無需改動演算法邏輯 | I/O 開銷大、恢復慢 |
| SuspendThread/ResumeThread | 無侵入式 | 極易死鎖、不安全、Windows 專用 |