国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

2020-01-24 02:50:33
字體:
供稿:網(wǎng)友

幾個(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);  //若已有其他線程占用鎖,則返回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) //輪詢直到獲得鎖
    {
        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;
}

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 瓦房店市| 河北区| 溆浦县| 万宁市| 崇仁县| 宕昌县| 东阳市| 白玉县| 明水县| 庆阳市| 无为县| 梅州市| 津南区| 新和县| 教育| 巴里| 大城县| 通化市| 怀宁县| 准格尔旗| 武川县| 清丰县| 巴林右旗| 交口县| 沙坪坝区| 奈曼旗| 松原市| 葫芦岛市| 岳阳县| 威海市| 五指山市| 沅江市| 七台河市| 图片| 郴州市| 吉木萨尔县| 梧州市| 察隅县| 金寨县| 商河县| 微山县|