首页 > 锁的粒度问题

锁的粒度问题

struct mg_context {
    char        *options[NUM_OPTIONS];    /* Configured opions    */
    pthread_mutex_t    opt_mutex[NUM_OPTIONS];    /* Option protector    */
    int        max_threads;    /* Maximum number of threads    */
    int        num_threads;    /* Number of threads        */
    int        num_idle;    /* Number of idle threads    */
    pthread_mutex_t    thr_mutex;    /* Protects (max|num)_threads    */
    pthread_cond_t    thr_cond;
    pthread_mutex_t    bind_mutex;    /* Protects bind operations    */
};

以上,每一个变量都有对应的锁,假设有一个线程获得了opt_mutex[0],然后需要对
options[0]这个字符串进行修改,然后又有一个线程需要修改max_threads,
那这个线程可以成功获得thr_mutex锁吗?如果能的话,它能立即就修改max_threads吗?

可以阿,这个锁能不能获取到是 跟这个锁有没有人在用这个锁有关系 跟其它的锁没有关系。。。
只要你要获取的锁不依赖于其它的锁(依赖的话其它的锁可能有人在用),就没有问题。。


完全可以啊,thr_mutex的获取跟opt_mutex是没有任何关系的,只要thr_mutex没有被其他线程锁住,你都可以获得到这个锁。你这里只给出了结构体,没有给出任何的操作逻辑。如果只从数据结构的角度来看,无论你获取跟不获取thr_mutex,都可以修改max_threads。

【热门文章】
【热门文章】