用pthread_cond_wait实现线程挂起的完整代码。
以下是使用pthread_cond_wait()实现线程挂起的完整代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t condition; // 条件变量
void* thread_func(void* arg) {
printf("Thread is waiting...\n");
// 等待条件变量满足
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condition, &mutex);
pthread_mutex_unlock(&mutex);
printf("Thread is awake!\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread; // 线程标识符
// 初始化互斥锁和条件变量
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condition, NULL);
// 创建线程
if (pthread_create(&thread, NULL, thread_func, NULL)) {
perror("Error creating thread");
exit(EXIT_FAILURE);
}
// 主线程等待一段时间后唤醒子线程
sleep(2);
printf("Main thread is waking up the other thread...\n");
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condition);
pthread_mutex_unlock(&mutex);
// 等待子线程结束
if (pthread_join(thread, NULL)) {
perror("Error joining thread");
exit(EXIT_FAILURE);
}
// 销毁互斥锁和条件变量
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condition);
return 0;
}
该程序创建一个子线程,子线程在等待条件变量满足时挂起,主线程等待一段时间后唤醒子线程。在子线程被唤醒后,它会打印一条消息,然后退出。程序退出时,会销毁互斥锁和条件变量。
原文地址: https://www.cveoy.top/t/topic/bw1w 著作权归作者所有。请勿转载和采集!