14. Operating system - mutex lock

Table of contents

1. Complete the installation of the POSIX man manual

2. Mutex lock

1. Basic knowledge of mutex

2. Operation steps

3、API

(1) pthread_mutex_init (initialize mutex)

(2) Lock/attempt to lock/unlock/destroy

 4. Code

5. Pay attention


1. Complete the installation of the POSIX man manual

sudo apt-get install manpages-posix-dev

2. Mutex lock

1. Basic knowledge of mutex

Mutual exclusion locks can be used to implement mutual exclusion logic (mutual exclusion locks can effectively protect a shared resource, so that only one thread can access the resource under any circumstances.)

2. Operation steps

(1) Initialize the mutex resource pthread_mutex_init()

(2) Lock pthread_mutex_lock() before accessing a resource

(3) pthread_mutex_unlock() should be unlocked after the access

(4) When it is no longer used, it should be destroyed to the lock resource pthread_mutex_destroy ( )

3、API

(1) pthread_mutex_init (initialize mutex)

(2) Lock/attempt to lock/unlock/destroy

 4. Code

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

//共享内存
char * mem_map = NULL ;

// 定义一个线程间可以互相访问的锁资源
pthread_mutex_t lock ;

void *FUNC(void * arg)
{
    while ( 1 )
    {
        // 阻塞等待锁资源
        printf("FUNC:等待锁资源获得!!\n");
        pthread_mutex_lock(&lock);
        printf("FUNC:成功获得锁资源并已上锁!!\n");
        printf("FUNC:收到的消息为:%s\n" , mem_map );
        sleep(1);
        // 解锁
        pthread_mutex_unlock(&lock);
        printf("FUNC:已解锁!!\n");
    }
}

int main(int argc, char const *argv[])
{
    // 先初始化线程间的“共享内存”
    mem_map = calloc(128 , 1 );

    // 初始化互斥锁
    if(pthread_mutex_init(&lock, NULL ))
    {
        perror("init error");
        return -1 ;
    }

    // 创建线程
    pthread_t thread ;
    pthread_create(&thread, NULL, FUNC , NULL ); 

    while ( 1 )
    {
        // 阻塞等待锁资源
        printf("MAIN:等待锁资源获得!!\n");
        pthread_mutex_lock(&lock);
        printf("MAIN:成功获得锁资源并已上锁!!\n");
        fgets(mem_map , 128 , stdin );
        sleep(1);
        // 解锁
        pthread_mutex_unlock(&lock);
        printf("MAIN:已解锁!!\n");
    }
    return 0;
}

5. Pay attention

A lock is a lock resource inside a process, and the resource disappears after restarting/killing the process

Guess you like

Origin blog.csdn.net/weixin_45981798/article/details/129883362