pthread库提供了两种方式来实现线程的挂起:

  1. pthread_cond_wait()函数:该函数会使线程进入等待状态,直到另一个线程调用pthread_cond_signal()pthread_cond_broadcast()函数来唤醒它。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

pthread_mutex_t mutex;
pthread_cond_t cond;

void* thread_func(void* arg) {
    pthread_mutex_lock(&mutex); // 加锁
    // 线程等待条件变量
    pthread_cond_wait(&cond, &mutex);
    pthread_mutex_unlock(&mutex); // 解锁
    // 此处执行线程被唤醒后的操作
    printf("Thread is woken up!
");
    return NULL;
}

int main() {
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, NULL);
    // 等待一段时间后唤醒线程
    sleep(5);
    pthread_mutex_lock(&mutex); // 加锁
    pthread_cond_signal(&cond); // 唤醒线程
    pthread_mutex_unlock(&mutex); // 解锁
    pthread_join(tid, NULL);
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);
    return 0;
}
  1. pthread_kill()函数:该函数会向指定线程发送一个信号,可以使用SIGSTOP信号来挂起线程。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>

void* thread_func(void* arg) {
    while (1) {
        // 线程执行操作
        printf("thread running
");
        sleep(1);
    }
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, NULL);
    // 等待一段时间后挂起线程
    sleep(5);
    pthread_kill(tid, SIGSTOP); // 挂起线程
    // 等待一段时间后恢复线程
    sleep(5);
    pthread_kill(tid, SIGCONT); // 恢复线程
    pthread_join(tid, NULL);
    return 0;
}
C语言pthread库线程挂起实现方法及代码示例

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

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