互斥量mutex的簡略應用(實例講授)。本站提示廣大學習愛好者:(互斥量mutex的簡略應用(實例講授))文章只能為提供參考,不一定能成為您想要的結果。以下是互斥量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); //解鎖
例程:
#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輸入會是50和200
b += 50; //加鎖後會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能先履行
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;
}