为什么在文件或结构中使用多个 Mutex?

why use multiple Mutex in a file or struct?

如果一个互斥量可以锁定一个变量区域,为什么要使用多个互斥量?

EX1 : (全局变量)

static DEFINE_MUTEX(core_list_lock);
static LIST_HEAD(core_list);
static DEFINE_MUTEX(module_list_lock);
static LIST_HEAD(module_list);

而不是

static DEFINE_MUTEX(lock);
static LIST_HEAD(core_list);
static LIST_HEAD(module_list);

EX2 : (对于结构)

struct core_data {
    struct list_head node;
    struct list_head module_list;
    char core_id[20];
    struct device *dev;
    struct list_head atten_list[CY_ATTEN_NUM_ATTEN];
    struct list_head param_list;
    struct mutex module_list_lock;
    struct mutex system_lock;
    struct mutex adap_lock;
    struct mutex hid_report_lock;
}

而不是

struct core_data {
    struct list_head node;
    struct list_head module_list;
    char core_id[20];
    struct device *dev;
    struct list_head atten_list[CY_ATTEN_NUM_ATTEN];
    struct list_head param_list;
    struct mutex lock;
}

我喜欢@klutt 的评论:Why have locks to individual rooms in a house when you can just have one lock on the front door?

我有一个使用两个互斥锁来改变两个自变量的小例子:int aint b

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int a, b;

pthread_mutex_t m1, m2;
void * increase_a(void * data) {
    for(int i = 0; i <10; i++) {
        pthread_mutex_lock(&m1);
        a++;
        printf("increase a = %d\n", a);
        pthread_mutex_unlock(&m1);
        sleep(1);
    }
}

void * decrease_a(void * data) {
    for(int i = 0; i <10; i++) {
        pthread_mutex_lock(&m1);
        a--;
        printf("decrease a = %d\n", a);
        pthread_mutex_unlock(&m1);
        sleep(1);
    }
}

void * increase_b(void * data) {
    for(int i = 0; i <10; i++) {
        pthread_mutex_lock(&m2);
        b++;
        printf("increase b = %d\n", b);
        pthread_mutex_unlock(&m2);
        sleep(1);
    }
}

void * decrease_b(void * data) {
    for(int i = 0; i <10; i++) {
        pthread_mutex_lock(&m2);
        b--;
        printf("decrease b = %d\n", b);
        pthread_mutex_unlock(&m2);
        sleep(1);
    }
}


int main()
{
    pthread_t a1, a2, b1, b2;

    pthread_create(&a1, NULL, increase_a, NULL);
    pthread_create(&a2, NULL, decrease_a, NULL);
    pthread_create(&b1, NULL, increase_b, NULL); 
    pthread_create(&b2, NULL, decrease_b, NULL);

    pthread_join(a1, NULL); 
    pthread_join(a2, NULL);
    pthread_join(b1, NULL);
    pthread_join(b2, NULL);

    pthread_mutex_destroy(&m1);
    pthread_mutex_destroy(&m2);


    return 0;
}

因为在这段代码中,ab是独立的(不共享内存,互不影响),所以可以把ab 同时.

如果使用一个互斥锁,则不能同时更改ab(例如,当您更改a时,其他线程无法访问b来更改它因为 a 在互斥锁下,当您更改 b 时,其他线程无法访问 a)。

但是当你使用两个互斥量时(一个用于 a,另一个用于 b),你可以同时更改 ab。这意味着,线程可以同时访问 ab