要安全终止所有正在运行的线程,可以采用以下步骤:

  1. 设计一个全局变量(如isRunning),用于控制线程是否继续运行的标志。初始时将其设置为true

  2. 在每个线程的循环中,使用该全局变量来判断是否继续执行任务。如果isRunningfalse,则跳出循环,线程终止。

  3. 当需要终止所有线程时,将全局变量isRunning设置为false

  4. 等待所有线程终止。可以使用thread.join()来等待每个线程的结束。

以下是一个简单的示例代码:

#include <iostream>
#include <thread>
#include <vector>

bool isRunning = true;

void threadFunction(int id) {
    while (isRunning) {
        // 线程执行的任务
        std::cout << "Thread " << id << " is running." << std::endl;
    }
    std::cout << "Thread " << id << " is terminated." << std::endl;
}

int main() {
    std::vector<std::thread> threads;
    int numThreads = 5;

    // 创建并启动所有线程
    for (int i = 0; i < numThreads; ++i) {
        threads.push_back(std::thread(threadFunction, i));
    }

    // 模拟运行一段时间后终止所有线程
    std::this_thread::sleep_for(std::chrono::seconds(2));
    isRunning = false;

    // 等待所有线程终止
    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}

在上述示例中,threadFunction函数是每个线程的入口点函数。每个线程在循环中检查isRunning的值,如果为false,则跳出循环,线程终止。在main函数中,首先创建并启动了指定数量的线程,然后等待一段时间后将isRunning设置为false,最后等待所有线程终止

mfc所有正在运行的线程怎么安全终止

原文地址: http://www.cveoy.top/t/topic/iU47 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录