GithubHelp home page GithubHelp logo

pyos-1's Introduction

PyOS

一个由Python coroutine实现的简化版操作系统

Under the hood

现在操作系统中,一般用进程来抽象正在运行的任务。进程有以下几个核心特征:

  1. 独立的控制流
  2. 独立的内部状态
  3. 可以被调度(挂起/恢复/关闭)
  4. 可以与其他进程通信

coroutine 具有上述特征:

  1. 一个coroutine本身也是一个subroutine(子过程),所以拥有独立的控制流
  2. 子过程拥有内部变量,可以用来保存内部状态
  3. 在一个coroutine中,yield可以将其挂起,send可以将其恢复,close可以将其关闭

至于进程的第四个特征(与其他进程通信),是由操作系统协助完成的。那么操作系统是如何在多个进程间进行调度的呢?

Interrupts and Traps

操作系统是通过中断(interrupts)与陷阱(traps)从正在运行的进程中获取控制权的。

  • 中断,一些硬件相关的信号,像I/O中断,时钟(timer)中断,键盘中断等
  • 陷阱,由软件产生的信号

当系统发生上面两种情况,CPU 把正在运行的进程挂起,把控制权转交给操作系统,这时操作系统就可以在多个任务间进行切换了。

Task Switching

yield语句可以看作是一种traps,利用这一点,我们就可以使用 Python 的 coroutine 来实现一个操作系统了。

Task Scheduler

Task Scheduler

这里实现的操作系统,核心是一个调度器,它里面主要包括两个队列:

  • Ready Queue,该队列中保存的是可以运行的任务
  • Wait Queue,该队列中保存的是可以需要等待的任务

Non-blocking I/O

使用select模块来监控活跃的 socketfile,示例代码:

reading = []    # List of sockets waiting for read
writing = []    # List of sockets waiting for write

# Poll for I/O activity
r,w,e = select.select(reading,writing,[],timeout)
# r is list of sockets with incoming data
# w is list of sockets ready to accept outgoing data
# e is list of sockets with an error state

堵塞型I/O类似于需要等待的任务,使用这种机制,就能够让这里的调度器支持异步I/O了。

main_echo.py

Reference

pyos-1's People

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.