CPU如何同时运行多个进程?

 1 # -*- coding: utf-8 -*-
 2 import re
 3 mem = [x for x in re.split('[\r|\n]', '''
 4 store a 1
 5 add a 1
 6 jmp -1
 7 store a 100
 8 add a -1
 9 jmp -1
10 '''.lower()) if x != '']
11 regs = {} # register file: 装register的柜子。register: 登记簿. pc: program counter
12 class ProcCxt: # Process Context
13     def __init__(this, pc): this.regs = {'pc' : pc} # this.priority ...
14 proc = [ProcCxt(0), ProcCxt(3)] # 2 processes
15 cpid = 0 # current process index
16 regs = proc[cpid].regs # start from process #0
17 while True:
18     inst = mem[regs['pc']].split() # fetch instruction 取指
19     print(inst, end='\t')
20     op_code = inst[0] # op: operation
21     if op_code == 'store':
22         (reg_name, immd) = inst[1:]
23         regs[reg_name] = int(immd)
24         regs['pc'] += 1
25     elif op_code == 'add':
26         (reg_name, immd) = inst[1:]
27         regs[reg_name] += int(immd)
28         if regs[reg_name] < 0: msb = 1
29         regs['pc'] += 1
30     elif op_code == 'jmp':
31         immd = int(inst[1])
32         if immd == 0: break
33         regs['pc'] += immd
34     print(regs)
35     if input('Interrupt [y/<Enter>]?').lower() == 'y':
36         proc[cpid].regs = regs
37         cpid = (cpid + 1) & 1
38         regs = proc[cpid].regs
39         print('switched to proc', cpid, regs)

以下内容过分追求简单,不准确。

CPU有几十个寄存器。linux kernel按task调度。历史上还有过batch, job等名词。ls && date是个job,ls和date是程序,运行起来后叫process,kernel里把process叫task。程序是死的、休眠的,在硬盘上存1万年还是那些个00101。进程是活的,有上下文。上面的程序A,B,C三个人运行,状况不一样——如果他们不是同时按y或Enter键的话。Sheldon有了Leonard Nimoy的DNA,种出两个来,分别在中国和美国生活,中国的会说“英语忒TM难学了”,美国的会说"OMG, there are thousands of characters?"

Windows 95前,Windows没有抢占式多任务。两个程序,一个调用get_data从网络收数据,另一个调用input从键盘读。这两个函数都是操作系统提供的:
void get_data() { if (data_not_ready) schedule(); ... }
void input() { if (data_not_ready) schedule(); ... }
void schedule() { 选个进程来运行。}

有了时钟中断,就可以每隔比如20ms,强行打断正在执行的进程,重新调度。没有时钟中断的话,网卡键盘等外设可能会有中断。while(1);的程序少,一般总要读写下文件吧。操作系统:heiheihei 有机可乘。

所谓进程在CPU上运行…… 其实程序是存在内存里的,多个CPU的多个核共享内存。每个核都是一大块电路,不同CPU的寄存器是不同的。所谓执行程序,就是寄存器,尤其是PC寄存器变来变去。

用python写进程调度器自然奇葩,不过linux也不是用汇编写的啊。当然它的调度器比round robin(圆桌骑士不是亚瑟吗?)花样多多了。

context switch

posted @ 2021-11-27 20:06  Fun_with_Words  阅读(960)  评论(0编辑  收藏  举报









 张牌。