文章目录

  • Motivation of Synchronization
    • Threads
    • Race Conditions and Reording
  • Implementation of Synchronization
    • Lock
      • Rules for using locks:
      • Lock implementation with Interrupts
      • Lock implementation with Atomic instruction sequences
    • Semaphores
      • Definition
      • Producer&Consumer with Bounded Buffer
      • Synchronization Problems using metaphore
      • Semaphore in UNIX
      • Implementation of Semaphore

Motivation of Synchronization

  • When threads concurrently read/write memory, program behavior is undefined.
  • Thread schedule is non-determinstic.
  • Also compiler/hardware instruction reordering and mulit-word operations are not atomic

Threads

1.Independent Threads
No state shared with other threads —> determinstic and reproducible.
2.Cooperating Threads
State shared with multiple threads —> nondeterminstic and non-reproducible.
cooperating threads
Most multi-thread process have both per-thread state(stack and registers which are stored in the TCB) and shared state(heap).

Race Conditions and Reording

Race conditions : What
Reording : Why

Implementation of Synchronization

Synchronization : using atomic operations to ensure cooperation between threads.
Mutual exclusion and critical section are two ways of describing the same thing.

Solutions by using Synchronization Variables
1.Lock
2.Condition Varibale
3.Semaphore

Lock

Lock before going to the critical section and before accessing the shared data.
Lock :: Acquire()
wait until lock is free
Lock :: Release()
release lock, waking up anyone waiting for it.

Rules for using locks:

  • lock is free initially
  • acquire before accessing the shared data and release after accessing the shared data
  • never access shared data without lock
  • example : bounded buffer

Lock implementation with Interrupts

Recall and analysis --> general idea is implementing locks by disabling/enabling interrupts.
Key idea : maintain a lock variable and impose mutual exlusion only during operations on that variable.

// the code between the dis/enable interrupt is called the critical section
int value = FREE;
Acquire() {disable interruptsif (value == BUSY) {put thread on wait queue;Go to sleep();// and The scheduler selects other threads// Enable interrupts?} else {value = BUSY;}enable interrupts;
}Release() {disable interrupts;if (anyone on wait queue) {take thread off wait queuePlace on ready queue;} else {value = FREE;}enable interrupts;
}

In the acquire, and value == Busy,

 if (value == BUSY) {put thread on wait queue;Go to sleep();// and The scheduler selects other threads// Enable interrupts?}

Actually we have 3 positions to enable the interrupts, and we have to choose the third one which is after go to sleep. The scheduler will do the following work because the thread doesn’t work after going to sleep.

How to enable interrupts after going to sleep?
Context Switch
In scheduler, since interrupts are disabled when you call sleep:Responsibility of the next thread to re-enable ints;
When the sleeping thread wakes up, returns to acquire and re-enables interrupts;

Lock implementation with Atomic instruction sequences

We have talked a lot about the lock, but interrupts are only available with the single CPU situation. If we have multiprocessor, we need other forms of lock.

Atomic Read-Modify-Write Instructions

  • Read-modify-write instructions
    Atomically read a value from memory, operate on it, and then write it back to memory
    Intervening instructions prevented in hardware(hardware implemented)
  • Examples
    Test and Set
    Exchange (Intel: xchgb, w/ lock prefix to make atomic)
    Compare and Swap
  • Any of these can be used for implementing locks and condition variables!
    test&set
test&set (&address) {           /* most architectures */result = M[address];        // return result from “address” andM[address] = 1;             // set value at “address” to 1 return result;
}

Implementing locks with test&set
Another flawed, but simple solution:

 int value = 0; // FreeAcquire() {while (test&set(value)); // while busy}Release() {value = 0;}
  • Simple explanation:
    If lock is free, test&set reads 0 and sets value=1, so lock is now busy. It returns 0 so while exits.
    If lock is busy, test&set reads 1 and sets value=1 (no change)
    It returns 1, so while loop continues.
    When we set value = 0, someone else can get lock.
  • Busy-Waiting: thread consumes cycles while waiting
    For multiprocessors: every test&set() is a write, which makes value ping-pong around in cache (using lots of network BW).
    Multiprocessor Spin Locks: test&test&set
    a better solution for multiprocessors:
 int mylock = 0; // FreeAcquire() {do {while(mylock);   // Wait until might be free} while(test&set(&mylock)); // exit if get lock}Release() {mylock = 0;}
  • Simple explanation:
    Wait until lock might be free (only reading – stays in cache and means the operation is atomic)
    Then, try to grab lock with test&set
    Repeat if fail to actually get lock
  • Issues with this solution:
    Busy-Waiting: thread still consumes cycles while waiting
    However, busy waiting but it does not impact other processors!
    通过以上讨论,我们需要Higher-level Primitives than Locks

Semaphores

Definition

First defined by Dijkstra in late 60s.
Main synchronization primitive used in original UNIX.
A Semaphore has a non-negative integer value and supports the following two operations:

  • P()/wait(): an atomic operation that waits for semaphore to become positive, then decrements it by 1. Think of this as the wait() operation. P不能将信号量降为负数
  • V()/signal(): an atomic operation that increments the semaphore by 1, waking up a waiting P, if any.

Explanation : Semaphores are a kind of generalized lock. However, the value of lock is treated as bool value as 0 and 1 while the semaphore value is non-negative integer value.

Binary Semaphore
The metaphore is initialled to be 1.(类比lock的话1就是unlocked的状态,因为一般锁初始化状态是unlocked,但有些时候也要初始化为0,比如实现某种特殊调度)
(同时1的话实现mutual exclusion)

Two uses of Semaphores

  1. mutual exclusion(lock)
    The lock function can be realized with a binary semaphore: semaphore subsumes lock.
    Semaphore has an initial value of 1
    P() is called before a critical section
    V() is called after the critical section
semaphore litter_box = 1;
P(litter_box);
// critical section
V(litter_box);
  1. synchronization
    Enforcing some order between threads(实现调度约束,semaphore is usually initialled to 0).

Producer&Consumer with Bounded Buffer

This is a simple but important problem.
Correctness constraints

  • Only one thread can manipulate buffer queue at a time (mutual exclusion)
  • When the buffer is full, producers must wait for consumers to consume a product (scheduling constraint)
  • When the buffer is empty, consumers must wait for producers to put a product (scheduling constraint)

Naturally , we can use a separate metaphore for each of the 3 constraints

semaphore mutex = 1; //for mutual exclusion
semaphore nFreeBuffers = N; // for producer
semaphore nLoadedBuffers = 0; // for consumer

Develop the solution

Producer() {P(nFreeBuffers);P(mutex);// put 1 item in the bufferV(mutex);V(nLoadedBuffers);
}Consumer() {P(nLoadedBuffers);P(mutex);// take 1 item from the bufferV(mutex);V(nFreeBuffers);
}

三点说明:
1.调换两个P位置会引起deadlock
2.调换两个V的位置没有关系
3.mutex是个二进制信号量(mutual exclusion),只有P(mutex)和V(mutex)之间的代码才是critical section,这部分要越小越好。

Synchronization Problems using metaphore

  • 读者写者问题
  • 哲学界进餐问题

Semaphore in UNIX

Managing concurrent access to shared memory. System resources.
Semaphore system calls

  • creation : semget(…)
  • incr/decr/set : semop(…)
  • deletion: semctl(semid, 0, IPC_RMID, 0);

Implementation of Semaphore

How to implement semaphore?

  • Almost exactly like lock.
  • Using spinlock or queue
    What hardware support is needed?
  • Interrupt disable
  • Test-and-set

Implement with interrupt with disable

class semaphore {int value;
}semaphore::semaphore(int i) {value = i;
}
semaphore::p() {// disable interruptswhile (value == 0) {// enable interrupts// disable interrupts}value --;// enable interrupts
}
semaphore::v() {// disable interruptsvalue ++;// enable interrupts
}

Implement with interrupt with test&set

class semaphore {int value;
}semaphore::semaphore(int i) {value = i;
}
semaphore::p() {while (test_and_set(guard));while (value == 0) {// queue the thread// guard = 0 and sleep}value --;guard = 0;
}
semaphore::v() {while (test_and_set(guard));if (anyone waiting) {// wake up one thread// put in on ready queue} else {value ++;}guard = 0;
}

Chapter5 Synchronization--操作系统翟岩龙老师相关推荐

  1. 【阿朱标红】O2O五年三次创业的九大经验(天天用车CEO翟光龙)

    注,来源于:小饭桌创业课堂,请大家关注[小饭桌]来的好文章.原标题为<天天用车CEO翟光龙:O2O五年三次创业总结出的九个关键词> 我整理完这篇文章,感觉作者主要讲的就是: 1.融资能力 ...

  2. 博士申请 | 香港理工大学滕龙老师课题组招收机器人方向博士生/研究助理

    合适的工作难找?最新的招聘信息也不知道? AI 求职为大家精选人工智能领域最新鲜的招聘信息,助你先人一步投递,快人一步入职! 香港理工大学 香港理工大学位于中国香港特别行政区,QS 最新排名-世界 6 ...

  3. 翼辉操作系统 linux,2K龙芯派翼辉SylixOS操作系统使用手册.PDF

    2K 龙芯派翼辉 SylixOS 操作系统使用手册 SylixOS 操作系统使用手册 User Manual PM0010010002 V1.00 Date: 2018/03/07 用户使用手册 类别 ...

  4. 进一步学习操作系统 - 哈工大李治军老师 - 学习笔记 L10L11L12

    这里写目录标题 L10 用户级线程 L11 内核级线程 L12 内核级线程实现 进程如何切换? L10 用户级线程 进程切换时,当前进程的CPU环境要保存,新进程的CPU环境要设置,线程切换时只须保存 ...

  5. 进一步学习操作系统 - 哈工大李治军老师 - 学习笔记 L26L27

    学习笔记-摘抄自老师书本内容 L26 I/O与显示器 L27 键盘 L26 I/O与显示器 使用外设: (1)向外设对应的端口地址发送 CPU 命令: (2)CPU 通过端口地址发送对外设的工作要求, ...

  6. 翼辉操作系统 linux,2K龙芯派翼辉SylixOS操作系统实验手册-翼辉信息.PDF

    2K龙芯派翼辉SylixOS操作系统实验手册-翼辉信息.PDF 目 录 一. 2K 龙芯派设备平台简介 1 1.1 Loongson2K1000 处理器介绍 1 1.1.1 芯片规格 1 1.1.2 ...

  7. 国产实时操作系统+intel x86/龙芯平台超边缘计算机方案

    引言 近年来,物联网.云计算.机器学习和网络安全等技术不断推动工业 4.0 的发展,"云边端" 的架构正逐步替代 "云管端",边缘计算成为新时代许多领域转型的关 ...

  8. 进一步学习操作系统 - 哈工大李治军老师 - 学习笔记 L28L29L30L31L32

    学习笔记 L28 生磁盘的使用 L29 从生磁盘到文件 L30 文件使用磁盘的实现 L31 目录与文件系统 L32 目录解析代码实现 完结撒花 L28 生磁盘的使用 要知道:柱面.盘面.磁道.扇区 磁 ...

  9. 进一步学习操作系统 - 哈工大李治军老师 - 学习笔记 L22L23L24L25

    学习笔记 L22 多级页表与快表 总结 L23 段页结合的实际内存管理 L24 内存换入-请求调页 L25 内存换出 L22 多级页表与快表 总结 32位地址,最大内存为232 = 4G 页面尺寸为4 ...

最新文章

  1. BigBiGAN问世,“GAN父”都说酷的无监督表示学习模型有多优秀?
  2. 跟随鼠标走的文字的html代码,跟随鼠标走的文字的HTML代码
  3. Docker 环境的快速搭建
  4. Linux PXE批量网络装机与Kickstart 无人值守安装
  5. 【Python CheckiO 题解】Between Markers
  6. 美图拟收购乐游科技附属公司约30%股份 后者为Warframe开发商
  7. erpc Linux 本地环境的搭建和使用
  8. coreldraw橙子怎么画_CDR绘制橙子和冰块教程
  9. IPQ6000 OpenWrt编译
  10. 《领导变革》读书笔记
  11. 共模干扰与差模干扰(及其消除)
  12. 微信小程序之九宫格布局方案
  13. 【学习打卡04】可解释机器学习笔记之Grad-CAM
  14. Android 录制桌面视频 screenrecord
  15. 机器学习----成本函数
  16. nginx 的离线编译安装
  17. OpenGL学习脚印: 绘制一个三角形
  18. 拿不到21.6万年薪退全款,廖雪峰大数据开发课程招生啦
  19. [sv] region timeslot
  20. Compose 动画艺术探索之 Easing

热门文章

  1. win7下IIS的安装和配置 图文教程
  2. 【SSL】勇闯黄金十二宫---射手宫
  3. android 按钮水纹,ope客户端英超f -官方网站
  4. SGMII和Serdes的差异
  5. python合并两个txt列_Python 合并多个TXT文件并统计词频的实现
  6. android读取所有图片分页打印,js控制分页打印、打印分页示例
  7. 出现“您的硬件设置已更改,请重新启动计算机,使这些更改生效”导致扬声器无法使用
  8. 在 Ubuntu 14.04 LTS 中配置 certbot 自动更新
  9. 星露谷物语联机服务器没有空闲位置6,星露谷物语多人联机教程 联机MOD怎么用...
  10. 腾讯云短信验证码接口调用案例