最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

互斥量mutex的簡(jiǎn)單使用(實(shí)例講解)

 更新時(shí)間:2014年01月22日 10:10:19   作者:  
本篇文章主要是對(duì)互斥量mutex的簡(jiǎn)單使用進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助

幾個(gè)重要的函數(shù):

#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是動(dòng)態(tài)分配的,則釋放內(nèi)存前調(diào)用此函數(shù)。

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

int pthread_mutex_trylock(pthread_mutex_t *mutex);  //若已有其他線(xiàn)程占用鎖,則返回EBUSY,否則返回0,不阻塞。

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

例程:

復(fù)制代碼 代碼如下:

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

int a = 100;
int b = 200;

pthread_mutex_t lock;

void * threadA()
{
    pthread_mutex_lock(&lock);
    printf("thread A got lock!\n");
    a -= 50;
    sleep(3);        //如果不加鎖,threadB輸出會(huì)是50和200
    b += 50;        //加鎖后會(huì)sleep 3秒后,并為b加上50 threadB才能打印
    pthread_mutex_unlock(&lock);
    printf("thread A released the lock!\n");
    a -= 50;
}

void * threadC()
{   
    sleep(1);
    while(pthread_mutex_trylock(&lock) == EBUSY) //輪詢(xún)直到獲得鎖
    {
        printf("thread C is trying to get lock!\n");
        usleep(100000);
    }
    printf("thread C got the lock!\n");
    a = 1000;
    b = 2000;
    pthread_mutex_unlock(&lock);
    printf("thread C released the lock!\n");

}

void * threadB()
{
    sleep(2);                //讓threadA能先執(zhí)行
    pthread_mutex_lock(&lock);
    printf("thread B got the lock! a=%d b=%d\n", a, b);
    pthread_mutex_unlock(&lock);
    printf("thread B released the lock!\n", a, b);
}

int main()
{
    pthread_t tida, tidb, tidc;
    pthread_mutex_init(&lock, NULL);
    pthread_create(&tida, NULL, threadA, NULL);
    pthread_create(&tidb, NULL, threadB, NULL);
    pthread_create(&tidc, NULL, threadC, NULL);
    pthread_join(tida, NULL);
    pthread_join(tidb, NULL);
    pthread_join(tidc, NULL);
    return 0;
}

相關(guān)文章

最新評(píng)論

浦县| 克东县| 任丘市| 基隆市| 德阳市| 灵丘县| 寿阳县| 大城县| 霍州市| 巴林右旗| 开原市| 浙江省| 博爱县| 胶州市| 荆州市| 江都市| 睢宁县| 长阳| 台北市| 平邑县| 安福县| 南陵县| 二连浩特市| 铜鼓县| 特克斯县| 南江县| 西乌珠穆沁旗| 大丰市| 中超| 阳江市| 顺平县| 分宜县| 广灵县| 尤溪县| 南投县| 洪湖市| 米林县| 六安市| 双峰县| 兴海县| 平潭县|