• 多线程的互斥锁的运用


    1、互斥锁的初始化pthread_mutex_init()函数语法

      

    2、互斥锁上锁、判断上锁、解锁、销毁锁pthread_mutex_函数语法

      

    代码分析:

    /* thread_mutex.c */
    #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 threads 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 joined failed
    ", no);
            }
            /* 互斥锁解锁 */
            pthread_mutex_unlock(&mutex);
        }
        pthread_mutex_destroy(&mutex);
        return 0;
    }

      

       

  • 相关阅读:
    LinuxShell脚本攻略--第八章 当个好管家
    LinuxShell脚本攻略--第六章 B计划
    LinuxShell脚本攻略--第三章 以文件之名
    LinuxShell脚本攻略--第二章 命令之乐
    LinuxShell脚本攻略--第一章 小试牛刀
    TCP/IP 与OSI结构图
    网络号和主机号的计算
    IP地址分类及私网IP
    转:Cache相关
    原码 反码 补码 移码
  • 原文地址:https://www.cnblogs.com/yihujiu/p/5597461.html
Copyright © 2020-2023  润新知