zoukankan      html  css  js  c++  java
  • 互斥量mutex的简单使用

    几个重要的函数:

    #include <pthread.h>

    int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutex_t *restrict attr);    //初始化mutex

    int pthread_mutex_destroy(pthread_mutex_t *mutex);  //如果mutex是动态分配的,则释放内存前调用此函数。

    int pthread_mutex_lock(pthread_mutex_t *mutex);    //加锁

    int pthread_mutex_trylock(pthread_mutex_t *mutex);  //若已有其他线程占用锁,则返回EBUSY,否则返回0,不阻塞。

    int pthread_mutex_unlock(pthread_mutex_t *mutex);   //解锁

    例程:

     1 #include <stdlib.h>
     2 #include <stdio.h>
     3 #include <unistd.h>
     4 #include <pthread.h>
     5 #include <errno.h>
     6 
     7 int a = 100;
     8 int b = 200;
     9 
    10 pthread_mutex_t lock;
    11 
    12 void * threadA()
    13 {
    14     pthread_mutex_lock(&lock);
    15     printf("thread A got lock!
    ");
    16     a -= 50;
    17     sleep(3);        //如果不加锁,threadB输出会是50和200
    18     b += 50;        //加锁后会sleep 3秒后,并为b加上50 threadB才能打印
    19     pthread_mutex_unlock(&lock);
    20     printf("thread A released the lock!
    ");
    21     a -= 50;
    22 }
    23 
    24 void * threadC()
    25 {    
    26     sleep(1);
    27     while(pthread_mutex_trylock(&lock) == EBUSY) //轮询直到获得锁
    28     {
    29         printf("thread C is trying to get lock!
    ");
    30         usleep(100000);
    31     }
    32     printf("thread C got the lock!
    ");
    33     a = 1000;
    34     b = 2000;
    35     pthread_mutex_unlock(&lock);
    36     printf("thread C released the lock!
    ");
    37     
    38 }
    39 
    40 void * threadB()
    41 {
    42     sleep(2);                //让threadA能先执行
    43     pthread_mutex_lock(&lock);
    44     printf("thread B got the lock! a=%d b=%d
    ", a, b);
    45     pthread_mutex_unlock(&lock);
    46     printf("thread B released the lock!
    ", a, b);
    47 }
    48 
    49 int main()
    50 {
    51     pthread_t tida, tidb, tidc;
    52     pthread_mutex_init(&lock, NULL);
    53     pthread_create(&tida, NULL, threadA, NULL);
    54     pthread_create(&tidb, NULL, threadB, NULL);
    55     pthread_create(&tidc, NULL, threadC, NULL);
    56     pthread_join(tida, NULL);
    57     pthread_join(tidb, NULL);
    58     pthread_join(tidc, NULL);
    59     return 0;
    60 }
  • 相关阅读:
    day50 初识JavaScript
    在C#中对Datatable排序【DefaultView的Sort方法】
    Windows Phone 中查找可视化树中的某个类型的元素
    抽象类(abstract)是否可以继承自实体类 ?
    C#遍历指定目录下的所有文件及文件夹
    Log4Net总结
    Firefox 与 IE 对Javascript和CSS的区别
    RSS 订阅
    Win8 URI 方案 ms-appX 用法大全
    ProgressIndicator显示进度条以及一些文字信息
  • 原文地址:https://www.cnblogs.com/ManMonth/p/3158152.html
Copyright © 2011-2022 走看看