温馨提示×

c++线程暂停和恢复的方法是什么

c++
小亿
118
2024-03-19 19:03:38
栏目: 编程语言

在C++中,线程的暂停和恢复并没有直接的方法。一种常见的方法是使用互斥锁和条件变量来实现线程的暂停和恢复。

具体步骤如下:

  1. 创建一个互斥锁和一个条件变量。
  2. 线程在执行过程中,通过互斥锁保护需要暂停和恢复的资源。
  3. 当线程需要暂停时,调用pthread_cond_wait()等待条件变量,并释放互斥锁。
  4. 当需要恢复线程时,调用pthread_cond_signal()或pthread_cond_broadcast()来唤醒线程,并重新获取互斥锁。

示例代码如下:

#include <iostream>
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t cond;

void* thread_func(void* arg) {
    pthread_mutex_lock(&mutex);
    std::cout << "Thread is running..." << std::endl;
    
    // 等待条件变量
    pthread_cond_wait(&cond, &mutex);
    
    std::cout << "Thread is resumed..." << std::endl;
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

int main() {
    pthread_t thread;
    
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    
    pthread_create(&thread, NULL, thread_func, NULL);
    
    // 主线程暂停1秒
    sleep(1);
    
    // 唤醒线程
    pthread_cond_signal(&cond);
    
    pthread_join(thread, NULL);
    
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);
    
    return 0;
}

上面的示例代码中,主线程创建了一个新线程并让其运行,然后暂停1秒后调用pthread_cond_signal()来唤醒线程。线程会在等待条件变量时暂停,并在条件变量被唤醒后继续执行。

0