C++并发函数实现:主函数触发停止运行中的randomFunction
解决方案:多线程实现中途停止循环
你的代码当前核心问题是主线程会先阻塞在randomFunction()的循环里,后面的for循环完全没有执行机会,自然无法调用stopFunction()终止循环。要实现“在randomFunction()运行时触发停止”,必须用多线程将循环逻辑和控制逻辑分开执行。
关键修改点
- 使用
std::thread将randomFunction()放到独立线程运行,让主线程能同时执行控制逻辑 - 用
std::atomic<int>修饰共享变量counter,避免多线程读写的竞态问题(保证线程间变量可见性和操作原子性)
修改后的完整代码
#include <iostream> #include <thread> #include <atomic> class A{ public: std::atomic<int> counter{0}; // 原子类型保证线程安全 void randomFunction() { while(counter != 1000) { int current = ++counter; std::cout << current << std::endl; } std::cout << "Task Complete!" << std::endl; } void stopFunction() { counter = 1000; } }; int main() { A o; // 创建子线程运行randomFunction std::thread t(&A::randomFunction, &o); for (int i = 0; i < 6; i++) { if (i == 5) { o.stopFunction(); } } // 等待子线程执行完成 t.join(); return 0; }
代码说明
std::atomic<int>:确保counter的读写操作是原子的,避免多个线程同时访问时出现未定义行为,同时保证一个线程修改counter后,其他线程能立即看到最新值。std::thread:将randomFunction()放到子线程执行,主线程可以继续运行for循环,当i=5时调用stopFunction()修改counter的值,触发子线程的循环终止。t.join():主线程等待子线程完成后再退出,避免程序提前结束导致子线程异常终止。
运行这段代码后,输出会符合你的预期:
1 2 3 4 5 Task Complete!
内容的提问来源于stack exchange,提问作者Victor Martinez
相关产品推荐
相关产品推荐

