Linux 多线程等待超时机制的实现:pthread_mutex_lock/pthread_cond_signal/pthread_mutex_unlock

最近在做一个项目,需要实现两个线程之间的等待超时机制。例如A线程等待B线程,需要实现等待超时机制。解决方案是利用条件变量实现。

1. 条件变量

    条件变量被用来阻塞一个线程,当条件不满足时,线程往往解开相应的互斥锁并等待条件发生变化。一旦其它的某个线程改变了条件变量,它将通知相应的条件变量唤醒一个或多个正被此条件变量阻塞的线程。这些线程将重新锁定互斥锁并重新测试条件是否满足。一般说来,条件变量被用来进行线承间的同步。

int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t * mutex, const struct timespec *abstime);

其中cond是一个指向结构pthread_cond_t的指针,cond_attr是一个指向结构pthread_condattr_t的指针。结构pthread_condattr_t是条件变量的属性结构,和互斥锁一样我们可以用它来设置条件变量是进程内可用还是进程间可用,默认值是PTHREAD_ PROCESS_PRIVATE,即此条件变量被同一进程内的各个线程使用。注意初始化条件变量只有未被使用时才能重新初始化或被释放。 

 

(1). pthread_cond_wait() : 使线程阻塞在一个条件变量上。线程解开mutex指向的锁并被条件变量cond阻塞。线程可以被函数pthread_cond_signal和函数pthread_cond_broadcast唤醒,但是要注意的是,条件变量只是起阻塞和唤醒线程的作用,具体的判断条件还需用户给出,例如一个变量是否为0等等,这一点我们从后面的例子中可以看到。线程被唤醒后,它将重新检查判断条件是否满足,如果还不满足,一般说来线程应该仍阻塞在这里,被等待被下一次唤醒。这个过程一般用while语句实现。

(2). pthread_cond_timedwait(): 它比函数pthread_cond_wait() 多了一个时间参数,经历abstime段时间后,即使条件变量不满足,阻塞也被解除。

(3). pthread_cond_signal(): 它用来释放被阻塞在条件变量cond上的一个线程。多个线程阻塞在此条件变量上时,哪一个线程被唤醒是由线程的调度策略所决定的。要注意的是,必须用保护条件变量的互斥锁来保护这个函数,否则条件满足信号又可能在测试条件和调用pthread_cond_wait函数之间被发出,从而造成无限制的等待。

2. 代码示例:

 

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#include <pthread.h>
#include <sys/time.h>
void root()
{
    ........

    pthread_mutex_lock(&mutex);
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
}

/**
 * Create a new thread to call root() and wait it completed.
 */
void start_root_and_timedwait()
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, (void *)root, NULL) != 0) {
        LOGE("############## Error: pthread_create failed ##############");
    } else {
        pthread_mutex_init(&mutex, NULL);
        pthread_cond_init(&cond, NULL);

        struct timeval now;
        struct timespec abstime;
        gettimeofday(&now, NULL);
        abstime.tv_sec = now.tv_sec + 60;//timeout = 60 seconds
        abstime.tv_nsec = now.tv_usec * 1000;

        pthread_mutex_lock(&mutex);
        pthread_cond_timedwait(&cond, &mutex, &abstime);
        pthread_mutex_unlock(&mutex);

        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&cond);

    }
}

注意:第一个参数&tid 不能设为NULL,否则创建thread 时进程会崩溃。

pthread_create(&tid, NULL, (void *)root, NULL)

转自:https://blog.csdn.net/wangbaochu/article/details/44946129 

pthread_mutex_init: 用于初始化互斥锁(mutex),将互斥锁设置为默认属性。 ```c #include <pthread.h> int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr); ``` pthread_cond_init: 用于初始化条件变量(condition variable),将条件变量设置为默认属性。 ```c #include <pthread.h> int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr); ``` pthread_create: 用于创建一个新的线程,并执行指定的函数。 ```c #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); ``` pthread_cond_signal: 用于唤醒一个等待在条件变量上的线程。 ```c #include <pthread.h> int pthread_cond_signal(pthread_cond_t *cond); ``` pthread_mutex_unlock: 用于解锁互斥锁,允许其他线程获取该互斥锁。 ```c #include <pthread.h> int pthread_mutex_unlock(pthread_mutex_t *mutex); ``` pthread_mutex_lock: 用于加锁互斥锁,如果互斥锁已经被锁定,则调用线程会阻塞直到互斥锁被解锁。 ```c #include <pthread.h> int pthread_mutex_lock(pthread_mutex_t *mutex); ``` 下面是一个使用这些函数的简单示例: ```c #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int count = 0; void* thread_func(void* arg) { pthread_mutex_lock(&mutex); // 检查条件是否满足 while (count < 10) { // 等待条件变量被唤醒 pthread_cond_wait(&cond, &mutex); } // 条件满足,执行任务 printf("Thread: Count is now %d\n", count); 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); // 模拟更新计数 for (int i = 0; i < 15; ++i) { pthread_mutex_lock(&mutex); count++; // 每次更新计数后,唤醒等待的线程 if (count >= 10) { pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); } // 等待线程结束 pthread_join(thread, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; } ``` 在上面的示例中,主线程更新一个计数器,当计数器达到10时,会通过条件变量唤醒等待的线程。等待的线程在条件满足时执行任务,并输出计数器的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值