- 论坛徽章:
- 3
|
原帖由 cjaizss 于 2008-12-20 00:06 发表 ![]()
如果是I/O操作都是原子的,且只有一读一写,对于具体程序应用而言,机器如何仲裁都无所谓,因为你没有需要避免的时序,也就是任何时序你都接受,那么就不需要锁了。除非像我之前举的例子那样,虽然I/O原子,但我 ...
而像之前我举的这个例子
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #define MAX 100000000
- volatile int x=0;
- void* thread(void* arg)
- {
- int i;
- for(i=0;i<MAX;i++)
- x++;
- }
- int main()
- {
- pthread_t id1,id2;
- pthread_create(&id1,NULL,thread,NULL);
- pthread_create(&id2,NULL,thread,NULL);
- pthread_join(id1,NULL);
- pthread_join(id2,NULL);
- printf("%d\n",x);
- return 0;
- }
复制代码
不一定会得到两倍MAX值
是因为x++不是原子操作
它由至少取地址上的存储,加一回写两个原子操作组成。
假设为a和b操作
线程为A,B
那么只要有
Aa,B....,Ab(中间全都是B线程的操作)
Ba,A....,Bb(中间全都是A线程的操作)
这样的时序存在,结果就不会正确,而在没有锁的情况下,这样的时序是很可能出现的 |
|