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);
     }
    }

  • 相关阅读:
    1136.NumberSteps
    1134.密码翻译
    1133.学分绩点
    1131.合唱队形
    1132.与7无关的数
    1130.日志排序
    Educational Codeforces Round 41 (Rated for Div. 2)
    Codeforces Round #378 (Div. 2) F
    Codeforces Round #290 (Div. 2)
    牛客网练习13 乌龟跑步
  • 原文地址:https://www.cnblogs.com/greencolor/p/2729667.html
Copyright © 2011-2022 走看看