可以使用条件变量和互斥锁来实现控制另一个方法 while 循环的暂停和重新启动循环。

具体实现步骤如下:

  1. 定义一个条件变量和一个互斥锁。
  2. 在 while 循环中使用互斥锁来保证线程安全。
  3. 在 while 循环中使用条件变量来实现暂停和重新启动循环。
  4. 在控制方法中使用互斥锁和条件变量来控制 while 循环的暂停和重新启动循环。

下面是示例代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

using namespace std;

mutex m;
condition_variable cv;
bool isPaused = false;

void loop() {
    while (true) {
        unique_lock<mutex> lock(m);
        while (isPaused) {
            cv.wait(lock);
        }
        cout << 'looping...' << endl;
        lock.unlock();
        this_thread::sleep_for(chrono::seconds(1));
    }
}

void control() {
    while (true) {
        char c;
        cin >> c;
        unique_lock<mutex> lock(m);
        if (c == 'p') {
            isPaused = true;
        } else if (c == 'r') {
            isPaused = false;
            cv.notify_one();
        }
        lock.unlock();
    }
}

int main() {
    thread t1(loop);
    thread t2(control);
    t1.join();
    t2.join();
    return 0;
}

在上面的示例代码中,loop() 方法是一个无限循环的方法,每次循环输出一句话并休眠 1 秒。在 while 循环中,使用互斥锁保证线程安全,使用条件变量来实现暂停和重新启动循环。

control() 方法是一个控制方法,不断读取用户输入的字符,如果是 'p' 则暂停循环,如果是 'r' 则重新启动循环。在控制方法中,使用互斥锁和条件变量来控制 while 循环的暂停和重新启动循环。

在主函数中,创建两个线程分别执行 loop() 和 control() 方法,并等待两个线程结束。

C++ 多线程控制:使用条件变量暂停和重启循环

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

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