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

  • 相关阅读:
    随机色块
    JQ命令汇总
    JQ选择器
    cookie
    tab切换
    Ajax跨域
    RocksDB介绍:一个比LevelDB更彪悍的引擎
    谷歌的诀窍:如何取消验证码
    Ruby on Rails创始人DHH谈如何进行混合移动APP开发
    SequoiaDB 架构指南
  • 原文地址:https://www.cnblogs.com/greencolor/p/2357502.html
Copyright © 2011-2022 走看看