zoukankan      html  css  js  c++  java
  • multi-threads synchronization use conditional mutex

    #include <pthread.h>
    int thread_flag;
    pthread_cond_t thread_flag_cv;
    pthread_mutex_t thread_flag_mutex;
    void initialize_flag ()
    {
    /* Initialize the mutex and condition variable.
    pthread_mutex_init (&thread_flag_mutex, NULL);
    pthread_cond_init (&thread_flag_cv, NULL);
    /* Initialize the flag value. */
    thread_flag = 0;
    }
    */
    /* Calls do_work repeatedly while the thread flag is set; blocks if
    the flag is clear. */
    void* thread_function (void* thread_arg)
    {
    /* Loop infinitely. */
    while (1) {
    /* Lock the mutex before accessing the flag value. */
    pthread_mutex_lock (&thread_flag_mutex);
    while (!thread_flag)
    /* The flag is clear. Wait for a signal on the condition
    variable, indicating that the flag value has changed. When the
    signal arrives and this thread unblocks, loop and check the
    flag again. */
    pthread_cond_wait (&thread_flag_cv, &thread_flag_mutex);
    /* When we’ve gotten here, we know the flag must be set. Unlock
    the mutex. */
    pthread_mutex_unlock (&thread_flag_mutex);
    /* Do some work. */
    do_work ();
    }
    return NULL;
    }
    /* Sets the value of the thread flag to FLAG_VALUE.
    */
    void set_thread_flag (int flag_value)
    {
    /* Lock the mutex before accessing the flag value. */
    pthread_mutex_lock (&thread_flag_mutex);
    /* Set the flag value, and then signal in case thread_function is
    blocked, waiting for the flag to become set. However,
    thread_function can’t actually check the flag until the mutex is
    unlocked. */
    thread_flag = flag_value;
    pthread_cond_signal (&thread_flag_cv);
    /* Unlock the mutex. */
    pthread_mutex_unlock (&thread_flag_mutex);
    }
  • 相关阅读:
    python 中 repr() 与str() 区别
    python高级特性 知识 架构总结
    python 递归 之加特技 汉诺塔
    python 递归 反转字符串
    git 的使用
    vim 常用命令
    ubuntu下零基础建站之python基础环境搭建
    Oracle 分组统计,抽取每组前十
    SQL Server2008知识点总结
    java 连接sql server2008配置
  • 原文地址:https://www.cnblogs.com/feika/p/3614517.html
Copyright © 2011-2022 走看看