您的位置:首页 > 编程语言

Posix多线程编程(1) 互斥锁与条件变量

2011-04-29 11:53 471 查看
今天学习了多线程互斥锁与条件变量,为了防止以后忘记,先记录一下总结的工作流程(主要是函数pthread_cond_timewait())。下面是Posix多线程编程中cond.c的代码(加入几条打印信息)。

]/*
 * cond.c
 *
 * Demonstrate a simple condition variable wait.
 */
#include <pthread.h>
#include <time.h>
#include "errors.h"
typedef struct my_struct_tag {
    pthread_mutex_t     mutex;  /* Protects access to value */
    pthread_cond_t      cond;   /* Signals change to value */
    int                 value;  /* Access protected by mutex */
} my_struct_t;
my_struct_t data = {
    PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0};
int hibernation = 1;            /* Default to 1 second */
/*
 * Thread start routine. It will set the main thread's predicate
 * and signal the condition variable.
 */
void *
wait_thread (void *arg)
{
    int status;
    sleep (hibernation);
    status = pthread_mutex_lock (&data.mutex);
    if (status != 0)
        err_abort (status, "Lock mutex");
    data.value = 1;             /* Set predicate */
    status = pthread_cond_signal (&data.cond);
    printf("send signal!/n");
    if (status != 0)
        err_abort (status, "Signal condition");
    status = pthread_mutex_unlock (&data.mutex);
    printf("after unlock!/n");
    if (status != 0)
        err_abort (status, "Unlock mutex");
    return NULL;
}
int main (int argc, char *argv[])
{
    int status;
    pthread_t wait_thread_id;
    struct timespec timeout;
    /*
     * If an argument is specified, interpret it as the number
     * of seconds for wait_thread to sleep before signaling the
     * condition variable.  You can play with this to see the
     * condition wait below time out or wake normally.
     */
    if (argc > 1)
        hibernation = atoi (argv[1]);
    /*
     * Create wait_thread.
     */
    status = pthread_create (&wait_thread_id, NULL, wait_thread, NULL);
    if (status != 0)
        err_abort (status, "Create wait thread");
    /*
     * Wait on the condition variable for 2 seconds, or until
     * signaled by the wait_thread. Normally, wait_thread
     * should signal. If you raise "hibernation" above 2
     * seconds, it will time out.
     */
    timeout.tv_sec = time (NULL) + 2;
    timeout.tv_nsec = 0;
    status = pthread_mutex_lock (&data.mutex);
    if (status != 0)
        err_abort (status, "Lock mutex");
    while (data.value == 0) {
        printf("into while/n");
        status = pthread_cond_timedwait (
            &data.cond, &data.mutex, &timeout);
    printf("after while!/n");
        if (status == ETIMEDOUT) {
            printf ("Condition wait timed out./n");
            break;
        }
        else if (status != 0)
            err_abort (status, "Wait on condition");
        printf("throuhgt/n");
    }
    if (data.value != 0)
        printf ("Condition was signaled./n");
    status = pthread_mutex_unlock (&data.mutex);
    printf("afte main unlock!/n");
    if (status != 0)
        err_abort (status, "Unlock mutex");
    return 0;
}




工作流程总结如下:

1、首先,主线程工作,锁住互斥锁,然后检测“谓词” value,结果value==0,所以进入循环,遇到函数pthread_cond_timewait()。

2、首先对mutex进行解锁,并等待条件变量cond(函数并未返回,而解锁立刻进行)。

3、此时被阻塞在互斥锁上的线程wait_thread被唤醒,锁住互斥锁,改变value值,发送信号,然后解锁。

4、主线程接收到信号,还是并不立刻返回,而是先上锁,然后返回。主线程继续运行,并测试value的值,value=1不满足while,从而退出循环,然后继续下面的工作。

(4)、由于用的是pthread_cond_timewait()函数,所以可能在主线程获得条件满足以前计时器已经超时,如果超时,函数上锁后立刻返回,并且break跳出循环,继续下面的处理。(不管什么情况,pthread_cond_timewait()函数返回之前一定会先上锁)



由于是初学,如果大家认为有什么不妥之处,还望不吝赐教!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: