https://jyywiki.cn/OS/2023/build/lect5.ipynb

多处理器编程入门

操作系统作为 “状态机的管理者”,引入了共享的状态

对hello.py,不同时间运行结果不一致

def Tprint(name):
  sys_write(f'{name}')

def main():
  for name in 'AB':
    sys_spawn(Tprint, name)

运行结果

运行结果

多线程共享内存并发

线程:共享内存的执行流

简化的线程 API (thread.h)

hello.c

#include "thread.h"

void Thello(int id) {
  while (1) {
    printf("%c", "_ABCDEFGHIJKLMNOPQRSTUVWXYZ"[id]);
  }
}

int main() {
  for (int i = 0; i < 10; i++) {
    create(Thello);
  }
}

thread.h

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdatomic.h>
#include <assert.h>
#include <unistd.h>
#include <pthread.h>

#define NTHREAD 64
enum { T_FREE = 0, T_LIVE, T_DEAD, };
struct thread {
  int id, status;
  pthread_t thread;
  void (*entry)(int);
};

struct thread tpool[NTHREAD], *tptr = tpool;

void *wrapper(void *arg) {
  struct thread *thread = (struct thread *)arg;
  thread->entry(thread->id);
  return NULL;
}

void create(void *fn) {
  assert(tptr - tpool < NTHREAD);
  *tptr = (struct thread) {
    .id = tptr - tpool + 1,
    .status = T_LIVE,
    .entry = fn,
  };
  pthread_create(&(tptr->thread), NULL, wrapper, tptr);
  ++tptr;
}

void join() {
  for (int i = 0; i < NTHREAD; i++) {
    struct thread *t = &tpool[i];
    if (t->status == T_LIVE) {
      pthread_join(t->thread, NULL);
      t->status = T_DEAD;
    }
  }
}

__attribute__((destructor)) void cleanup() {
  join();
}

运行结果

运行结果