SoFunction
Updated on 2025-03-07

Simple use of mutex mutex (example explanation)

Several important functions:

#include <>

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);    // Add lock

int pthread_mutex_trylock(pthread_mutex_t *mutex);  //If other threads already occupy the lock, return EBUSY, otherwise return 0 and do not block.

int pthread_mutex_unlock(pthread_mutex_t *mutex);   //Unlock

Routine:

Copy the codeThe code is as follows:

#include <>
#include <>
#include <>
#include <>
#include <>

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 the lock is not added, the threadB output will be 50 and 200
b += 50;         //After locking, sleeping for 3 seconds, and add 50 threadB to b before printing
    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 the lock is obtained
    {
        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);                                                                                                                             �
    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;
}