#include <windows.h>
#include <process.h>
using namespace std;
void print(void){
for(int i = 0; i < 10; ++i){
cout << "num:" << i << endl;
Sleep(1000);
}
}
int flag[2] = {0};
int turn = 0;
void thread(void *num){
int val = (int)(num);
flag[val] = 1;
turn = 1;
while(flag[1 - val] && turn){
print();
}
}
void test(){
int one = 1;
int zero = 0;
_beginthread(thread, 0, (void*)one);
_beginthread(thread, 0, (void*)zero);
}
进程中的空间是相互独立,访问数据时候只有建共享内存,管道等,才能完成彼此间通信,使数据访问非常麻烦;
线程中就相对比较容易,可以直接访问共享数据,但是必须避免同时访问。例如:原子,互斥锁,自旋锁,信号量可以避免同时访问带来的麻烦。
Peterson算法也可以实现类似的功能。
wiki里面提供了很详细的解释,我就不在这里重复了,贴出地址: http://zh.wikipedia.org/wiki/Peterson%E7%AE%97%E6%B3%95