zoukankan      html  css  js  c++  java
  • semaphore

    #include <stdio.h>     // printf(),
    #include <stdlib.h>    // exit(), EXIT_SUCCESS
    #include <pthread.h>   // pthread_create(), pthread_join()
    #include <semaphore.h> // sem_init()

    sem_t binSem;

    void* helloWorld(void* arg);

    int main() {
      // Result for System call
      int res = 0;
      int i= 0;

      // Initialize semaphore
      res = sem_init(&binSem, 0, 0);
      if (res) {
        printf("Semaphore initialization failed!!\n");
        exit(EXIT_FAILURE);
      }

      // Create thread
      pthread_t thdHelloWorld;
      res = pthread_create(&thdHelloWorld, NULL, helloWorld, NULL);
      if (res) {
        printf("Thread creation failed!!\n");
        exit(EXIT_FAILURE);
      }

      for ( i=1; i <  10; i++) {
        // Post semaphore
        sleep(1);

        sem_post(&binSem);
      }

      // Wait for thread synchronization
      void *threadResult;
      res = pthread_join(thdHelloWorld, &threadResult);
      if (res) {
        printf("Thread join failed!!\n");
        exit(EXIT_FAILURE);
      }

      exit(EXIT_SUCCESS);
    }

    void* helloWorld(void* arg) {
      while(1) {
        // Wait semaphore
        sem_wait(&binSem);
        printf("Hello World\n");
      }
    }

  • 相关阅读:
    zookeeper与activemq最新存储replicatedLevelDB整合
    MySQL分表的3种方法
    mycat 从入门到放弃 (转)
    centos 7 忘记密码
    java内存溢出的情况解决方法
    跨域问题的产生及解决方法
    一次jvm调优过程
    2019年总结
    Jenkinsfile与Json的转换
    DevOps平台
  • 原文地址:https://www.cnblogs.com/greencolor/p/2357502.html
Copyright © 2011-2022 走看看