zoukankan      html  css  js  c++  java
  • 互斥锁与条件变量应用 2014-06-01 22:20 328人阅读 评论(0) 收藏

    一个经典的条件变量与互斥锁的应用。程序如下:


    #include<pthread.h>
    #include<stdio.h>
    #include<stdlib.h>
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    struct node
    {
      int number;
      struct node *next;
    } *head = NULL;
    void *thread (void *arg)
    {
      struct node *p;
      while (1)
      {
        pthread_mutex_lock (&mutex);
        while (head == NULL)
          pthread_cond_wait (&cond, &mutex);
        p = head;
        head = head->next;
        printf ("Got %d from front of queue
    ", p->number);
        free (p);
        pthread_mutex_unlock (&mutex);
      }
      return NULL;
    }
    
    int main (int argc, char *argv[])
    {
      pthread_t tid;
      int i;
      struct node *p;
      pthread_create (&tid, NULL, thread, NULL);
      for (i = 0; i < 10; i++)
      {
        p = malloc (sizeof (struct node));
        pthread_mutex_lock (&mutex);
        p->number = i;
        p->next = head;
        head = p;
        pthread_cond_signal (&cond);
        pthread_mutex_unlock (&mutex);
        sleep (1);
      }
      pthread_cancel (tid);
      int result;
      pthread_join (tid,NULL);
      printf ("done,exit");
      return 0;
    }

    刚开对此程序不太理解,经过查阅资料终于搞清楚了一些细节问题

    1.条件变量必须和互斥锁一起使用,应为条件变量是全局变量,需要防止多个线程同时对条件变量wait操作。

    2.pthread_cond_wait()函数内部包含一对解锁和加锁操作:在进入pthread_cond_wait()前,调用线程已经加锁;

    进入pthread_cond_wait()后,线程加入条件变量等待队列,此时解开互斥锁。当等待条件被满足时,线程退出

    pthread_cond_wait(),同时尝试对互斥锁加锁来访问临界区变量。

    3.pthread_cond_signal在多处理器上可能同时唤醒多个线程当你只能让一个线程处理某个任务时,其它被唤

    的线程就需要继续挂起等待,故使用循环测试(如上例的while (head == NULL))。

    4.pthread_cancel (tid)的作用是向线程tid发送退出请求,线程会继续运行至取消点退出,该例的取消点是

    pthread_cond_wait(),若注释掉该句,则子线程会一直在pthread_cond_wait()中等待,程序结束不了。

     

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    day04 列表和元组
    Python2和Python3的区别
    Ruby学习笔记2 : 一个简单的Ruby网站,搭建ruby环境
    Patrick Hughes
    Ruby学习笔记1 -- 基本语法和数据类型, Class
    Javascript学习笔记5
    php学习笔记1——使用phpStudy进行php运行环境搭建与测试。
    Linux配置和管理msyql命令
    干净win7要做几步才能运行第一个Spring MVC 写的动态web程序
    The difference between Spring Tool Suite and Spring IDE
  • 原文地址:https://www.cnblogs.com/luo-peng/p/4646267.html
Copyright © 2011-2022 走看看