zoukankan      html  css  js  c++  java
  • 信号量和互斥量C语言示例理解线程同步

    线程同步

    了解线程信号量的基础知识,对深入理解python的线程会大有帮助。

    当两个线程同时执行时,不可避免同时操作同一个变量或者文件等,所以需要有一组机制来确保他们能正确的运行:信号量和互斥量。信号量可以分为最简单的“二进制信号量”和更通用的“计数信号量”。信号量通常用来保护一段代码,使其每次只能被一个执行线程运行,这种情况下需要用到二进制信号量。有时候希望可以允许有限数目的线程执行一段指定代码,这就需要用到计数信号量。实际上,技术信号量是一种二进制信号量的逻辑扩展,实际两者调用的函数一样。

    互斥量和信号量很相似,事实上他们可以互相通过对方来实现。但在实际应用中,对于一些情况使用其中一种更符合语义而且效果更好。

    用信号量进行同步

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    #include <pthread.h>
    #include <semaphore.h>
    
    void *thread_function(void *arg);
    sem_t bin_sem;
    
    #define WORK_SIZE 1024
    char work_area[WORK_SIZE];      /* 用来存放输入内容 */
    
    int main() {
      int res;                    /* 暂存一些命令的返回结果 */
      pthread_t a_thread;         /* 织带新建的线程 */
      void *thread_result;       /* 存放线程处理结果 */
    
      res = sem_init(&bin_sem, 0, 0);   /* 初始化信号量,并且设置初始值为0*/
      if (res != 0) {
        perror("Semaphore initialization failed");
        exit(EXIT_FAILURE);
      }
      res = pthread_create(&a_thread, NULL, thread_function, NULL);   /* 创建新线程 */
      if (res != 0) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
      }
      printf("Inout some text, Enter 'end' to finish
    ");
      while(strncmp("end", work_area, 3) != 0) {             /* 当工作区内不是以end开头的字符串时...*/
        fgets(work_area, WORK_SIZE, stdin);                  /* 从标准输入获取输入到worl_area */
        sem_post(&bin_sem);                                  /* 信号量+1 */
      }
      printf("
    Waiting for thread to finish...
    ");
      res = pthread_join(a_thread, &thread_result);         /* 等待线程结束 */
      if (res != 0) {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
      }
      printf("Thread joined
    ");
      sem_destroy(&bin_sem);                               /* 销毁信号量 */
      exit(EXIT_SUCCESS);
    }
    
    void *thread_function(void *arg) {
      sem_wait(&bin_sem);                                 /* 等待信号量有大于0的值然后-1 */
      while(strncmp("end", work_area, 3) != 0) {
        printf("You input %ld characters
    ", strlen(work_area)-1);   /* 获取输入字符串长度 8*/
        sem_wait(&bin_sem);                               /* 等待信号量有大于0的值然后-1 */
      }
      pthread_exit(NULL);
    }
    

    用互斥量进行同步

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    #include <pthread.h>
    #include <semaphore.h>
    
    void *thread_function(void *arg);
    pthread_mutex_t work_mutex;
    
    #define WORK_SIZE 1024
    char work_area[WORK_SIZE];
    int time_to_exit = 0;                           /* 用来控制是否退出*/
    
    int main() {
      int res;
      pthread_t a_thread;
      void *thread_result;
    
      res = pthread_mutex_init(&work_mutex,NULL);    /* 初始化一个互斥锁 */
      if (res != 0) {
        perror("Mutex initialization failed");
        exit(EXIT_FAILURE);
      }
      res = pthread_create(&a_thread, NULL, thread_function, NULL);  /* 创建一个新线程 */
      if (res != 0) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
      }
      pthread_mutex_lock(&work_mutex);                       /* 尝试对互斥量加锁 */
      printf("Input some text, Enter 'end' to finish
    ");
      while(!time_to_exit) {                                   /* 检查是不是该退出*/
        fgets(work_area, WORK_SIZE, stdin);                   /* 从标准输入获取输入到work_area */
        pthread_mutex_unlock(&work_mutex);                   /* 解锁互斥量 */
        while(1) {
          pthread_mutex_lock(&work_mutex);
          if (work_area[0] != '') {                      /* 持续检查work_area 是否为空, 如果不为空继续等待,如果为空,则重新读取输入到work_area*/
            pthread_mutex_unlock(&work_mutex);
            sleep(1);
          }
          else {
            break;
          }
        }
      }
      pthread_mutex_unlock(&work_mutex);
      printf("
    Waiting for thread to finish...
    ");
      res = pthread_join(a_thread, &thread_result);
      if (res != 0) {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
      }
      printf("Thread joined
    ");
      pthread_mutex_destroy(&work_mutex);
      exit(EXIT_SUCCESS);
    }
    
    void *thread_function(void *arg) {
      sleep(1);
      pthread_mutex_lock(&work_mutex);                     /* 尝试加锁互斥量 */
      while(strncmp("end", work_area, 3) != 0) {           /* 当work_area里的值不是以end开头时*/
        printf("You input %ld characters
    ", strlen(work_area) -1);     /* 输出输入的字符长度 */
        work_area[0] = '';                                      /* work_area设置为空 */
        pthread_mutex_unlock(&work_mutex);
        sleep(1);
        pthread_mutex_lock(&work_mutex);
        while (work_area[0] == '') {              /* 持续检查work_area 直到它里面有输入值*/
          pthread_mutex_unlock(&work_mutex);
          sleep(1);
          pthread_mutex_lock(&work_mutex);
        }
      }
      time_to_exit = 1;                        /* 当输入end后,设置退出标志 */
      work_area[0] = '';
      pthread_mutex_unlock(&work_mutex);
      pthread_exit(0);
    }
    

    参考资料

    • 《Beginning Linux Programming》
  • 相关阅读:
    ThinkPHP之APP_DEBUG给我带来的问题
    yii框架部署
    论文翻译之--- 软件设计师怎样使用标记来帮助提醒和重新查找
    初始html5,遇到的第一个问题
    几种进入mysql的方法
    百度经验---一些生活常见问题的解决
    myeclipse背景色设置遇到的问题
    linux学习(二)-----Linux 的目录结构、远程登录、vi和vim
    linux学习(一)-----vm、centos安装
    springboot核心技术(四)-----Docker、数据访问、自定义starter
  • 原文地址:https://www.cnblogs.com/nisen/p/6083866.html
Copyright © 2011-2022 走看看