CLOCK_MONOTONIC 和 pthread_mutex_timedlock pthread_cond_timedwait

作者:编程家 分类: c++ 时间:2025-07-28

使用 CLOCK_MONOTONIC 和 pthread_mutex_timedlock / pthread_cond_timedwait 进行多线程同步

概述

在多线程编程中,同步操作是非常重要的,以确保线程之间的正确执行顺序和共享资源的安全访问。在某些情况下,我们可能希望在一段时间后超时退出等待状态,或者在等待一段时间后执行某些操作。这时,我们可以使用 CLOCK_MONOTONIC 时钟和 pthread_mutex_timedlock / pthread_cond_timedwait 函数来实现。

CLOCK_MONOTONIC

CLOCK_MONOTONIC 是 Linux 系统中的一种时钟类型,它以纳秒为单位提供了一个连续递增的系统范围时钟。与其他时钟类型(如 CLOCK_REALTIME)不同,CLOCK_MONOTONIC 不受系统时间的更改影响,因此更适合用于测量时间间隔和超时等操作。

pthread_mutex_timedlock

pthread_mutex_timedlock 函数用于在一段时间内尝试获取一个互斥锁。如果在指定的时间内未能获取到锁,则函数将返回 ETIMEDOUT 错误。这个函数可以用于避免线程长时间等待某个操作完成而无法继续执行的情况。

pthread_cond_timedwait

pthread_cond_timedwait 函数用于在一段时间内等待条件变量的满足。如果在指定的时间内条件变量未满足,则函数将返回 ETIMEDOUT 错误。这个函数可以用于在等待某个条件满足时,避免线程长时间等待而无法继续执行的情况。

案例代码

下面是一个使用 CLOCK_MONOTONIC 时钟和 pthread_mutex_timedlock / pthread_cond_timedwait 函数的案例代码,展示了如何在多线程环境下实现超时等待和同步操作。

c

#include

#include

#include

#include

pthread_mutex_t mutex;

pthread_cond_t cond;

void* thread_func(void* arg) {

struct timespec timeout;

clock_gettime(CLOCK_MONOTONIC, &timeout);

timeout.tv_sec += 5; // 等待 5 秒钟

pthread_mutex_lock(&mutex);

int ret = pthread_cond_timedwait(&cond, &mutex, &timeout);

if (ret == 0) {

printf("Condition satisfied!\n");

} else if (ret == ETIMEDOUT) {

printf("Timeout!\n");

}

pthread_mutex_unlock(&mutex);

return NULL;

}

int main() {

pthread_t thread;

pthread_mutex_init(&mutex, NULL);

pthread_cond_init(&cond, NULL);

pthread_create(&thread, NULL, thread_func, NULL);

// 假设这里有一些其他耗时操作

sleep(10);

pthread_mutex_lock(&mutex);

pthread_cond_signal(&cond);

pthread_mutex_unlock(&mutex);

pthread_join(thread, NULL);

pthread_mutex_destroy(&mutex);

pthread_cond_destroy(&cond);

return 0;

}

上述代码中,我们创建了一个线程,在线程中等待条件变量的满足。我们使用 CLOCK_MONOTONIC 时钟获取当前时间,并在此基础上计算出超时时间。然后使用 pthread_mutex_timedlock 函数尝试获取互斥锁,在获取锁后调用 pthread_cond_timedwait 函数等待条件变量的满足。在主线程中,我们执行了一些其他耗时操作后,通过发送信号使得条件变量满足,并在子线程中进行相应的处理。

通过使用 CLOCK_MONOTONIC 时钟和 pthread_mutex_timedlock / pthread_cond_timedwait 函数,我们可以在多线程环境下实现超时等待和同步操作,提高程序的可靠性和效率。