• 一个线程和信号量的例子


    ///编译时加上-lpthread
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/ioctl.h>
    #include <pthread.h>
    
    #include <semaphore.h>
    sem_t sem1,sem2;
    
    void fun(void *arg)
    {
     printf("fall asleep
    ");
     sem_wait(&sem1);printf(" 1
    ");sem_post(&sem2);
     sem_wait(&sem1);printf(" 3
    ");sem_post(&sem2);
     sem_wait(&sem1);printf(" 5
    ");sem_post(&sem2);
     sem_wait(&sem1);printf(" 7
    ");sem_post(&sem2);
     sem_wait(&sem1);printf(" 9
    ");sem_post(&sem2);
     sem_wait(&sem1);printf(" 11
    ");sem_post(&sem2);
     exit(EXIT_FAILURE);
    }
    
    int main()
    {
     pthread_t thread;
     int arg=1,res;
     sem_init(&sem1,0,0);
     sem_init(&sem2,0,0);
     res=pthread_create(&thread,PTHREAD_CREATE_JOINABLE,(void*)fun,NULL);
     if(res)
     {
      printf("pthread_create error!
    ");
      exit(EXIT_FAILURE);
     }
     sleep(1);
     sem_post(&sem1);sem_wait(&sem2);printf("2
    ");
     sem_post(&sem1);sem_wait(&sem2);printf("4
    ");
     sem_post(&sem1);sem_wait(&sem2);printf("6
    ");
     sem_post(&sem1);sem_wait(&sem2);printf("8
    ");
     sem_post(&sem1);sem_wait(&sem2);printf("10
    ");
     sem_post(&sem1);sem_wait(&sem2);printf("12
    ");
     pthread_join(thread,NULL);
     return 0;
    }
  • 相关阅读:
    枚举定义三个常量--遍历如下
    初始化和赋值的概念
    javascript 事件
    HTML 5 本地存储
    html5 说明
    JQuery 双击动态编辑
    ThinkPHP 3.2.2 事务
    PHP AJAX JSONP实现跨域请求使用实例
    chorme 插件
    frontend-tools
  • 原文地址:https://www.cnblogs.com/CoderTian/p/4200780.html
Copyright © 2020-2023  润新知