你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux下多任务间通信和同步-条件变量

[日期:2013-11-27] 来源:Linux社区  作者:ce123 [字体:大 中 小]

系统调用pthread_cond_broadsignal()

该系统调用通知所有线程条件已经满足.其原型为:

#include <pthread.h>
int pthread_cond_broadsignal(pthread_cond_t*cond);

与pthread_cond_signal()函数不同,该调用将通知等待该条件的所有线程.

系统调用pthread_cond_destroy()

该系统调用清楚动态分配的互斥锁变量。其原型为:

#include <pthread.h>
int pthread_cond_destroy(pthread_cond_t*cond);

条件变量的应用实例

/**************************************************************************************/
/*简介:互斥锁和条件变量同步线程演示程序      */
/*************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t count_lock;
pthread_cond_t count_ready;
int count;

void *decrement_count(void *arg)
{
        pthread_mutex_lock(&count_lock);
        printf("decrement:waiting\n");
        /*等待满足条件,期间互斥量仍然可用*/
        while (count == 0)
                pthread_cond_wait(&count_ready, &count_lock);
        count = count - 1;
        printf("decrement:count = %d\n",  count);
        pthread_mutex_unlock(&count_lock);
        pthread_exit(NULL);
}

void *increment_count(void *arg)
{
        pthread_mutex_lock(&count_lock);
        printf("increment:running\n");
        count = count + 1;
        /*通知线程条件已满足*/
        pthread_cond_signal(&count_ready);

        printf("increment:count = %d\n",  count);
        pthread_mutex_unlock(&count_lock);
        pthread_exit(NULL);
}

int main()
{
        pthread_t tid1,tid2;
        count=0;
        pthread_mutex_init(&count_lock, NULL);
        pthread_cond_init(&count_ready, NULL);

        pthread_create(&tid1, NULL, decrement_count, NULL);
        sleep(1);
        pthread_create(&tid2, NULL, increment_count, NULL);
        /*等待decrement退出*/
        pthread_join(tid2, NULL);
 printf("decrement quit\n");
        pthread_join(tid1, NULL);
        return 0;
}

linux
相关资讯       Linux条件变量 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款