zoukankan      html  css  js  c++  java
  • pthread_mutex_t pthread_mutex_init pthread_mutex_lock pthread_mutex_unlock pthread_delay_np

    void reader_function ( void );
    void writer_function ( void );

    char buffer;
    int buffer_has_item=0;
    pthread_mutex_t mutex;
    struct timespec delay;
    void main ( void ){
     pthread_t reader;
     /* 定义延迟时间*/
     delay.tv_sec = 2;
     delay.tv_nec = 0;
     /* 用默认属性初始化一个互斥锁对象*/
     pthread_mutex_init (&mutex,NULL);
     pthread_create(&reader, pthread_attr_default, (void *)&reader_function), NULL);
     writer_function( );
    }

    void writer_function (void){
     while(1){
      /* 锁定互斥锁*/
      pthread_mutex_lock (&mutex);
      if (buffer_has_item==0){
       buffer=make_new_item( );
       buffer_has_item=1;
      }
      /* 打开互斥锁*/
      pthread_mutex_unlock(&mutex);
      pthread_delay_np(&delay);
     }
    }

    void reader_function(void){
     while(1){
      pthread_mutex_lock(&mutex);
      if(buffer_has_item==1){
       consume_item(buffer);
       buffer_has_item=0;
      }
      pthread_mutex_unlock(&mutex);
      pthread_delay_np(&delay);
     }
    }

  • 相关阅读:
    [ZJOI2010] 数字计数
    [USACO] 2004 Open MooFest 奶牛集会
    数星星
    [SCOI2011] 糖果
    西瓜种植
    [NOI2018] 归程
    [APIO2012] 派遣
    小K的农场
    妮可妮可妮 [Hash]
    [ZJOI2012] 灾难
  • 原文地址:https://www.cnblogs.com/greencolor/p/2729667.html
Copyright © 2011-2022 走看看