Simple use of the of example for the mutex mutex
- 2020-06-12 10:17:42
- OfStack
A few important functions:
#include < pthread.h >
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutex_t *restrict attr); // Initialize mutex
int pthread_mutex_destroy (pthread_mutex_t * mutex); // If mutex is dynamically allocated, this function is called before freeing memory.
int pthread_mutex_lock (pthread_mutex_t * mutex); / / lock
int pthread_mutex_trylock (pthread_mutex_t * mutex); // Return EBUSY if the lock is already held by another thread, otherwise return 0, no blocking.
int pthread_mutex_unlock (pthread_mutex_t * mutex); / / unlock
Routine:
#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); // If you leave it unlocked, threadB The output will be 50 and 200
b += 50; // After locking sleep 3 After seconds, and is b add 50 threadB To print
pthread_mutex_unlock(&lock);
printf("thread A released the lock!\n");
a -= 50;
}
void * threadC()
{
sleep(1);
while(pthread_mutex_trylock(&lock) == EBUSY) // Poll until you get the lock
{
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); // let threadA Can you perform
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;
}