为什么要在文件或结构中使用多个互斥锁?

问题描述 投票:0回答:1

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

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;
}
c mutex
1个回答
1
投票

我喜欢@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

© www.soinside.com 2019 - 2024. All rights reserved.