作業系統›Ch6 行程同步(Process Synchronization)第 7 題/共 32 題
7. Atomicity Violation、Race Condition、Lock
#OS-06-007中Atomicity ViolationRace ConditionLock
The atomicity violation bug occurs when multiple operations intend to run an indivisible (atomic) unit, but are interrupted by another thread in concurrent programs. The atomicity violation bugs result in the desired serializability among multiple memory accesses being violated, leading to lost updates. Please choose the correct atomicity violation bug code pattern(s) below.
(a)
static int i = 0;
static object a, b = default;
var tid1 = Task.Run(() => {
lock(a) {i++;}
});
var tid2 = Task.Run(() => {
lock(b) {i++;}
});
Task.WhenAll(tid1, tid2); print(i);
(b)
static pthread_cond_var WorkDone = PTHREAD_COND_INIT;
void main() {
pthread_id tid = null;
pthread_create(&tid, NULL, &fun, NULL);
pthread_wait(&WorkDone);
}
void fun() { pthread_singal(&WorkDone); }
(c)
static int i = 0;
var tid1 = Task.Run(() => {
if (atomic_load(&i) == 0) {
atomic_add(&i, 1);
}
});
var tid2 = Task.Run(() => {
if (atomic_load(&i) == 0) {
atomic_add(&i, 1);
}
});
Task.WhenAll(tid1, tid2); print(i);
(d)
static long int i = 101;
var tid1 = Task.Run(() => {
i++;
});
var tid2 = Task.Run(() => {
print(i);
});
Task.WhenAll(tid1, tid2);
📄 交大115
▤完整推導請見《WH 資工筆記 · 作業系統》Ch6 行程同步(Process Synchronization)