程序员的自我修养 -- 链接、装载与库

首先声明,这是一本好书。:)


-- 但是存在一些问题,也有可能是我理解的不够。。 ?


2012.11.22

1.6.2 线程安全

互斥量(Mutex)描述说,哪个线程获取了互斥量,哪个线程就要负责释放,其他线程越俎代庖去释放互斥量是无效的。

---------------------------------

这里说法是错误的,最起码针对Linux实现的pthread_mutex是错误的。

一个简单的测试程序即可验证上述错误:

#include <pthread.h>

#include <stdio.h>

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *thread(void *arg)
{
        int i = 1;

        while (1) {
                printf("Now i'll try to unlock ... %d\n", i++);
                pthread_mutex_unlock(&lock);
                sleep(3);
        }
}

int main()
{
        int i = 1;
        pthread_t td;
        pthread_create(&td, NULL, thread, NULL);


        while (1)
        {
                printf("Before mutex_lock... %d\n", i);
                pthread_mutex_lock(&lock);
                printf("After mutex_lock... %d\n", i);
                ++i;
        }

        return 0;
}
yanyg@yvit ~$ gcc -o test test.c -lpthread
yanyg@yvit ~$ ./test
Before mutex_lock... 1
After mutex_lock... 1
Before mutex_lock... 2
Now i'll try to unlock ... 1
After mutex_lock... 2
Before mutex_lock... 3
Now i'll try to unlock ... 2
After mutex_lock... 3
Before mutex_lock... 4
Now i'll try to unlock ... 3
After mutex_lock... 4
Before mutex_lock... 5

“过度优化”一节的描述:

所有论述的结果表达的含义是加锁也不能保证多线程安全,需要添加内存屏障。这真实从何谈起。哪位在开发用户程序时在锁之外还添加内存屏障了?

对于Linux实现互斥锁而言,如果无法获取mutex,则执行系统调用sys_futex,sys_futex自会保障有序性,换句话说,保证有序是lock的份内责任。

否则,何谈多线程同步开发?

其关于双检测的说法也犯了同样的错误。


ps, 我在wiki上查看mutex定义,也没看出定义中或者实现上有这个限制:

In computer science, mutual exclusion refers to the problem of ensuring that no two processes or threads (henceforth referred to only as processes) can be in their critical section at the same time. Here, a critical section refers to a period of time when the process accesses a shared resource, such as shared memory. The problem of mutual exclusion was first identified and solved by Edsger W. Dijkstra in his seminal 1965 paper titled: Solution of a problem in concurrent programming control.

也有可能windows平台的实现另有玄机吧?

------

此外,作者对于三种线程模型的看法,与我颇有差异,不过此处无硬伤,不提也罢了。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值