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);
    }
  • 相关阅读:
    mysql重复数据下,删除一条重复数据
    Mysql常用函数
    鼠标滑至某位置,在鼠标旁边出现详情弹窗div
    限制文本框只能输入正数,负数,小数
    JAVA中split对空串的影响。
    《JAVA与模式》之简单工厂模式 (转)
    linux 常用命令汇总
    《JAVA与模式》之责任链模式
    《JAVA与模式》之模板方法模式 (转)
    java 异常汇总
  • 原文地址:https://www.cnblogs.com/feika/p/3614517.html
Copyright © 2011-2022 走看看