我目前正在学jyy的操作系统,该文章为我的笔记。
学习链接 : 链接点击跳转

并发的:同时存在、发生或完成的。在计算机科学中,并发指的是一个程序、算法或问题的不同部分或单元按无序或部分顺序执行而不影响最终结果的能力。







__thread 特性:线程局部变量 == 依附于在每一个线程上 TLS 有指针








/ xxx 查找xxx




T1T2的实现
#include "thread.h"
int x = 0, y = 0;
atomic_int flag; // 0 close 1 open
#define FLAG atomic_load(&flag)
#define FLAG_XOR(val) atomic_fetch_xor(&flag, val) //异或操作
#define WAIT_FOR(cond) while (!(cond)) ;
__attribute__((noinline))
void write_x_read_y() {
int y_val;
asm volatile(
"movl $1, %0;" // x = 1
"movl %2, %1;" // y_val = y
: "=m"(x), "=r"(y_val) : "m"(y)
);
printf("%d ", y_val);
}
__attribute__((noinline))
void write_y_read_x() {
int x_val;
asm volatile(
"movl $1, %0;" // y = 1
"movl %2, %1;" // x_val = x
: "=m"(y), "=r"(x_val) : "m"(x)
);
printf("%d ", x_val);
}
void T1(int id) {
while (1) {
WAIT_FOR((FLAG & 1));
write_x_read_y();
FLAG_XOR(1);
}
}
void T2() {
while (1) {
WAIT_FOR((FLAG & 2));//等待全部
write_y_read_x();
FLAG_XOR(2);
}
}
void Tsync() {
while (1) {
x = y = 0;
__sync_synchronize(); // full barrier
usleep(1); // + delay
assert(FLAG == 0);
FLAG_XOR(3); // change to
// T1 and T2 clear 0/1-bit, respectively
WAIT_FOR(FLAG == 0);
printf("\n"); fflush(stdout);
}
}
int main() {
create(T1);
create(T2);
create(Tsync);
}


mfence保证内存写入到共享内存以后,才执行下一条指令,来保证内存的一致性






