zoukankan      html  css  js  c++  java
  • linux多线程编程之互斥锁

      多线程并行运行,共享同一种互斥资源时,需要上互斥锁来运行,主要是用到pthread_mutex_lock函数和pthread_mutex_unlock函数对线程进行上锁和解锁

      下面是一个例子:

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>

    #define THREAD_NUMBER        3            /* 线程数 */
    #define REPEAT_NUMBER        3            /* 每个线程的小任务数 */
    #define DELAY_TIME_LEVELS 10.0         /*小任务之间的最大时间间隔*/
    pthread_mutex_t mutex;

    void *thrd_func(void *arg)
    {
         int thrd_num = (int)arg;
         int delay_time = 0, count = 0;
         int res;
         /* 互斥锁上锁 */
         res = pthread_mutex_lock(&mutex);
         if (res)
         {
              printf("Thread %d lock failed ", thrd_num);
              pthread_exit(NULL);
         }
         printf("Thread %d is starting ", thrd_num);
         for (count = 0; count < REPEAT_NUMBER; count++)
         {         
         delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX)) + 1;
         sleep(delay_time);
         printf(" Thread %d: job %d delay = %d ",
                                      thrd_num, count, delay_time);
         }
         printf("Thread %d finished ", thrd_num);
         pthread_exit(NULL);
    }

    int main(void)
    {
         pthread_t thread[THREAD_NUMBER];
         int no = 0, res;
         void * thrd_ret;
        
         srand(time(NULL));
         /* 互斥锁初始化 */
         pthread_mutex_init(&mutex, NULL);
         for (no = 0; no < THREAD_NUMBER; no++)
         {
              res = pthread_create(&thread[no], NULL, thrd_func, (void*)no);//创建多个线程
              if (res != 0)
              {
                  printf("Create thread %d failed ", no);
                  exit(res);
              }
         }    
         printf("Create treads success Waiting for threads to finish... ");
         for (no = 0; no < THREAD_NUMBER; no++)
         {
              res = pthread_join(thread[no], &thrd_ret);
              if (!res)
              {
              printf("Thread %d joined ", no);
              }
              else
              {
                  printf("Thread %d join failed ", no);
              }
              /* 互斥锁解锁 */
              pthread_mutex_unlock(&mutex);
         }    
         pthread_mutex_destroy(&mutex);         
         return 0;       
    }

    一切来自对linux嵌入式的热爱

  • 相关阅读:
    Junit单元测试
    win7的6个网络命令
    WOJ1024 (POJ1985+POJ2631) Exploration 树/BFS
    WOJ1022 Competition of Programming 贪心 WOJ1023 Division dp
    woj1019 Curriculum Schedule 输入输出 woj1020 Adjacent Difference 排序
    woj1018(HDU4384)KING KONG 循环群
    woj1016 cherry blossom woj1017 Billiard ball 几何
    woj1013 Barcelet 字符串 woj1014 Doraemon's Flashlight 几何
    woj1012 Thingk and Count DP好题
    woj1010 alternate sum 数学 woj1011 Finding Teamates 数学
  • 原文地址:https://www.cnblogs.com/hedengfeng/p/3443073.html
Copyright © 2011-2022 走看看