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

  • 相关阅读:
    分布式集群环境下运行Wordcount程序
    VM搭建hadoop分布式集群
    安装运行Hadoop
    网络问题
    Golang依赖工具
    会话进程组终端 · 守护进程
    Golang笔记
    [转]GDB
    [转]用户态与内核态
    【转】linux环境内存分配原理 malloc info
  • 原文地址:https://www.cnblogs.com/greencolor/p/2357502.html
Copyright © 2011-2022 走看看