MIT XV6 - 1.3 Lab: Xv6 and Unix utilities - primes

接上文 MIT XV6 - 1.2 Lab: Xv6 and Unix utilities - pingpong

primes

繼續實驗,實驗介紹和要求如下 (原文鏈接 譯文鏈接) :

Write a concurrent prime sieve program for xv6 using pipes and the design illustrated in the picture halfway down this page and the surrounding text. This idea is due to Doug McIlroy, inventor of Unix pipes. Your solution should be in the file user/primes.c.

Your goal is to use pipe and fork to set up the pipeline. The first process feeds the numbers 2 through 35 into the pipeline. For each prime number, you will arrange to create one process that reads from its left neighbor over a pipe and writes to its right neighbor over another pipe. Since xv6 has limited number of file descriptors and processes, the first process can stop at 35.

Some hints:

  • Be careful to close file descriptors that a process doesn’t need, because otherwise your program will run xv6 out of resources before the first process reaches 35.
  • Once the first process reaches 35, it should wait until the entire pipeline terminates, including all children, grandchildren, &c. Thus the main primes process should only exit after all the output has been printed, and after all the other primes processes have exited.
  • Hint: read returns zero when the write-side of a pipe is closed.
  • It’s simplest to directly write 32-bit (4-byte) ints to the pipes, rather than using formatted ASCII I/O.
  • You should create the processes in the pipeline only as they are needed.
  • Add the program to UPROGS in Makefile.

大致意思呢,參考 Unix pipes的創造者,大佬Doug McIlroy的 Bell Labs and CSP Threads,基于多進程和管道來篩選一定范圍內的素數.

在這里插入圖片描述
什么意思呢,每個進程呢就像一個過濾器,把自己處理不了的數據扔給下一級,我是這么理解的啊,這樣可能更符合這個實驗?

地鐵路上想好了怎么寫,回來一遍過

/** Prime Number Sieve using Pipes* * This program implements the Sieve of Eratosthenes algorithm using pipes and processes* to find prime numbers concurrently. The algorithm works as follows:* * 1. Each process represents a prime number and filters out its multiples* 2. Numbers are passed through pipes between processes* 3. Each process reads numbers from its left pipe and writes non-multiples to its right pipe* * Process Communication Flow:* * Process 1 (2) -> Process 2 (3) -> Process 3 (5) -> Process 4 (7) -> ...*    [pipe1]         [pipe2]         [pipe3]          [pipe4]* * Each process:* 1. Reads numbers from left pipe* 2. If number is not divisible by its prime, passes it to right pipe* 3. Creates new child process for first number it receives* * Example flow for numbers 2-10:* * Time   Process 1    Process 2    Process 3    Process 4* ---------------------------------------------------------* t0      reads 2      -            -            -* t1      sends 3      reads 3      -            -* t2      sends 5      sends 5      reads 5      -* t3      sends 7      sends 7      sends 7      reads 7* t4      sends 9      reads 9      -            -* * Note: Numbers 4, 6, 8, 10 are filtered out by Process 1 (multiples of 2)*       Numbers 9 is filtered out by Process 2 (multiple of 3)*       Only prime numbers reach their corresponding processes*/#include "kernel/types.h"
#include "user/user.h"// Constants for prime number calculation
#define START_PRIME 2        // First prime number to start with
#define MAX_PRIMES 35       // Maximum number to check for primes// Pipe file descriptor constants
#define PIPE_INVALID -1      // Invalid pipe descriptor
#define PIPE_READ 0          // Read end of pipe
#define PIPE_WRITE 1         // Write end of pipe/*** Prints a prime number to the console* @param n The prime number to print*/
void print_prime(int n) { printf("prime %d\n", n); }/*** Safely closes a pipe file descriptor if it's valid* @param p The pipe file descriptor to close*/
void close_pipe_if_valid(int p) {if (p != PIPE_INVALID) {close(p);}
}/*** Delivers a number through the pipe system and creates new processes for primes* @param n The number to process* @param pipe_left The left pipe for receiving numbers*/
void deliver_prime(int n, int pipe_left[2]) {// If pipe is not initialized, create it and fork a new processif (pipe_left[PIPE_WRITE] == PIPE_INVALID) {int ret = pipe(pipe_left);if (ret < 0) {exit(1);}ret = fork();if (ret == 0) {// Child processclose_pipe_if_valid(pipe_left[PIPE_WRITE]);// Print the prime number this process representsprint_prime(n);// Initialize right pipe for passing numbers to next processint pipe_right[2] = {PIPE_INVALID, PIPE_INVALID};int received_number = 0;// Read numbers from left pipe and filter themwhile (read(pipe_left[PIPE_READ], &received_number,sizeof(received_number)) > 0) {// Skip numbers that are multiples of current primeif (received_number % n == 0) {continue;}// Pass non-multiples to next processdeliver_prime(received_number, pipe_right);}// Clean up pipesclose_pipe_if_valid(pipe_left[PIPE_READ]);close_pipe_if_valid(pipe_right[PIPE_READ]);close_pipe_if_valid(pipe_right[PIPE_WRITE]);// Wait for child process to completewait(0);exit(0);} else if (ret > 0) {// Parent process continues} else {printf("fork error, current index: %d\n", n);exit(1);}} else {// printf("deliver_prime: %d\n", n);// Write number to pipeif (write(pipe_left[PIPE_WRITE], &n, sizeof(n)) <= 0) {exit(1);}}
}/*** Main function that initiates the prime number calculation* @param argc Number of command line arguments* @param argv Command line arguments* @return 0 on successful execution*/
int main(int argc, char *argv[]) {// Initialize pipe for first processint p[2] = {PIPE_INVALID, PIPE_INVALID};// Print the first prime numberprint_prime(START_PRIME);// Process numbers from START_PRIME + 1 to MAX_PRIMESfor (int i = START_PRIME + 1; i <= MAX_PRIMES; i++) {// Skip multiples of START_PRIMEif (i % START_PRIME == 0) {continue;}// Process the number through the pipe systemdeliver_prime(i, p);}// Clean up pipesclose(p[PIPE_READ]);close(p[PIPE_WRITE]);// Wait for child process to completewait(0);return 0;
}

實驗結果

make qemu
qemu-system-riscv64 -machine virt -bios none -kernel kernel/kernel -m 128M -smp 3 -nographic -global virtio-mmio.force-legacy=false -drive file=fs.img,if=none,format=raw,id=x0 -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0xv6 kernel is bootinghart 1 starting
hart 2 starting
init: starting sh
$ primes
prime 2
prime 3
prime 5
prime 7
prime 11
prime 13
prime 17
prime 19
prime 23
prime 29
prime 31

他實驗中提到一點 Since xv6 has limited number of file descriptors and processes, the first process can stop at 35.,于是我把 MAX_PRIMES改成了100并加了一些錯誤日志,試一下什么時候會"資源耗盡"。

make qemu
qemu-system-riscv64 -machine virt -bios none -kernel kernel/kernel -m 128M -smp 3 -nographic -global virtio-mmio.force-legacy=false -drive file=fs.img,if=none,format=raw,id=x0 -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0xv6 kernel is bootinghart 2 starting
hart 1 starting
init: starting sh
$ primes
prime 2
prime 3
prime 5
prime 7
prime 11
prime 13
prime 17
prime 19
prime 23
prime 29
prime 31
prime 37
prime 41
pipe error, current index: 43
$ 

為什么是43?留個坑吧…

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/80512.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/80512.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/80512.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

hive兩個表不同數據類型字段關聯引發的數據傾斜

不同數據類型引發的Hive數據傾斜解決方案 #### 一、?原因分析? 當兩個表的關聯字段存在數據類型不一致時&#xff08;如int vs string、bigint vs decimal&#xff09;&#xff0c;Hive會觸發隱式類型轉換引發以下問題&#xff1a; ?Key值的精度損失?&#xff1a;若關聯字…

【JAVA】業務系統訂單號,流水號生成規則工具類

設計業務系統訂單號&#xff0c;流水號注意事項 唯一性&#xff1a;確保在分布式環境下ID不重復 有序性&#xff1a;ID隨時間遞增&#xff0c;有利于數據庫索引性能 可讀性&#xff1a;包含時間信息&#xff0c;便于人工識別 擴展性&#xff1a;支持業務前綴和類型區分 性能…

【嵌入式開發-SPI】

嵌入式開發-SPI ■ SPI簡介■ SPI &#xff08;Standard SPI&#xff09;■ DSPI &#xff08;Dual SPI&#xff09;■ QSPI是 Queued SPI的簡寫 ■ SPI簡介 SPI協議其實是包括&#xff1a;Standard SPI、Dual SPI和Queued SPI三種協議接口&#xff0c;分別對應3-wire, 4-wire…

基于HTTP頭部字段的SQL注入:SQLi-labs第17-20關

前置知識&#xff1a;HTTP頭部介紹 HTTP&#xff08;超文本傳輸協議&#xff09;頭部&#xff08;Headers&#xff09;是客戶端和服務器在通信時傳遞的元數據&#xff0c;用于控制請求和響應的行為、傳遞附加信息或定義內容類型等。它們分為請求頭&#xff08;Request Headers&…

基于Qt開發的http/https客戶端

成果展示&#xff1a; 使用Qt開發HTTP客戶端主要依賴QNetworkAccessManager、QNetworkRequest和QNetworkReply三大核心類。以下是具體實現要點及最佳實踐&#xff1a; 一、核心類與基礎流程?? 1.QNetworkAccessManager?? 作為HTTP請求的管理者&#xff0c;負責異步處理…

自適應蒙特卡洛定位-AMCL

自適應蒙特卡洛定位&#xff0c;簡稱AMCL&#xff0c;主要提供定位功能并以/tf形式輸出 蒙特卡洛算法的基本思想&#xff1a;當所要求的問題是某種事件出現的概率或者是某個變量的期望值時&#xff0c;它們可以通過某種"試驗"的方法&#xff0c;得到這種事件出現的概…

魯濱遜歸結原理詳解:期末考點+解題指南

1. 引言 歸結原理&#xff08;Resolution Principle&#xff09; 是自動定理證明和邏輯推理的核心技術&#xff0c;由約翰艾倫羅賓遜&#xff08;John Alan Robinson&#xff09;于1965年提出。它是一階謂詞邏輯的機械化推理方法&#xff0c;廣泛應用于人工智能&#xff08;如…

華為云Flexus+DeepSeek征文|DeepSeek-V3/R1商用服務開通教程以及模型體驗

在當今數字化浪潮迅猛推進的時代&#xff0c;云計算與人工智能技術的深度融合正不斷催生出眾多創新應用與服務&#xff0c;為企業和個人用戶帶來了前所未有的便利與發展機遇。本文將重點聚焦于在華為云這一行業領先的云計算平臺上&#xff0c;對 DeepSeek-V3/R1 商用服務展開的…

Matlab基于PSO-MVMD粒子群算法優化多元變分模態分解

Matlab基于PSO-MVMD粒子群算法優化多元變分模態分解 目錄 Matlab基于PSO-MVMD粒子群算法優化多元變分模態分解效果一覽基本介紹程序設計參考資料效果一覽 基本介紹 PSO-MVMD粒子群算法優化多元變分模態分解 可直接運行 分解效果好 適合作為創新點(Matlab完整源碼和數據),以包…

自然語言處理NLP中的連續詞袋(Continuous bag of words,CBOW)方法、優勢、作用和程序舉例

自然語言處理NLP中的連續詞袋&#xff08;Continuous bag of words&#xff0c;CBOW&#xff09;方法、優勢、作用和程序舉例 目錄 自然語言處理NLP中的連續詞袋&#xff08;Continuous bag of words&#xff0c;CBOW&#xff09;方法、優勢、作用和程序舉例一、連續詞袋( Cont…

商業模式解密:鳴鳴很忙下沉市場的隱憂,破局之路在何方?

文 | 大力財經 作者 | 魏力 在零售行業的版圖中&#xff0c;“鳴鳴很忙”憑借獨特的商業模式&#xff0c;在下沉市場異軍突起&#xff0c;成為不可忽視的力量。555億GMV、廣泛的縣域覆蓋以及高比例的鄉鎮門店&#xff0c;無疑彰顯了其在下沉市場的王者地位。然而&#xff0c;…

YOLOv5推理代碼解析

代碼如下 import cv2 import numpy as np import onnxruntime as ort import time import random# 畫一個檢測框 def plot_one_box(x, img, colorNone, labelNone, line_thicknessNone):"""description: 在圖像上繪制一個矩形框。param:x: 框的坐標 [x1, y1, x…

CATIA高效工作指南——常規配置篇(二)

一、結構樹&#xff08;Specification Tree&#xff09;操作技巧精講 結構樹是CATIA設計中記錄模型歷史與邏輯關系的核心模塊&#xff0c;其高效管理直接影響設計效率。本節從基礎操作到高級技巧進行系統梳理。 1.1 結構樹激活與移動 ??激活方式??&#xff1a; ??白線…

批量重命名bat

作為一名程序員&#xff0c;怎么可以自己一個個改文件名呢&#xff01; Windows的批量重命名會自動加上括號和空格&#xff0c;看著很不爽&#xff0c;寫一個bat處理吧&#xff01;?(ゝω???) 功能&#xff1a;將當前目錄下的所有文件名里面當括號和空格都去掉。 用法&…

嵌入式軟件開發常見warning之 warning: implicit declaration of function

文章目錄 &#x1f9e9; 1. C 編譯流程回顧&#xff08;背景&#xff09;&#x1f4cd; 2. 出現 warning 的具體階段&#xff1a;**編譯階段&#xff08;Compilation&#xff09;**&#x1f9ec; 2.1 詞法分析&#xff08;Lexical Analysis&#xff09;&#x1f332; 2.2 語法分…

【人工智能-agent】--Dify中MCP工具存數據到MySQL

本文記錄的工作如下&#xff1a; 自定義MCP工具&#xff0c;爬取我的鋼鐵網數據爬取的數據插值處理自定義MCP工具&#xff0c;把爬取到的數據&#xff08;str&#xff09;存入本地excel表格中自定義MCP工具&#xff0c;把爬取到的數據&#xff08;str&#xff09;存入本地MySQ…

Golang 應用的 CI/CD 與 K8S 自動化部署全流程指南

一、CI/CD 流程設計與工具選擇 1. 技術棧選擇 版本控制&#xff1a;Git&#xff08;推薦 GitHub/GitLab&#xff09;CI 工具&#xff1a;Jenkins/GitLab CI/GitHub Actions&#xff08;本文以 GitHub Actions 為例&#xff09;容器化&#xff1a;Docker Docker Compose制品庫…

網絡基礎1(應用層、傳輸層)

目錄 一、應用層 1.1 序列化和反序列化 1.2 HTTP協議 1.2.1 URL 1.2.2 HTTP協議格式 1.2.3 HTTP服務器示例 二、傳輸層 2.1 端口號 2.1.1 netstat 2.1.2 pidof 2.2 UDP協議 2.2.1 UDP的特點 2.2.2 基于UDP的應用層…

基于大模型預測的吉蘭 - 巴雷綜合征綜合診療方案研究報告大綱

目錄 一、引言(一)研究背景(二)研究目的與意義二、大模型預測吉蘭 - 巴雷綜合征的理論基礎與技術架構(一)大模型原理概述(二)技術架構設計三、術前預測與手術方案制定(一)術前預測內容(二)手術方案制定依據與策略四、術中監測與麻醉方案調整(一)術中監測指標與數…

【言語】刷題2

front&#xff1a;刷題1 ? 前對策的說理類 題干 新時代是轉型關口&#xff0c;要創新和開放&#xff08;前對策&#xff09;創新和開放不能一蹴而就&#xff0c;但是對于現代化很重要 BC片面&#xff0c;排除 A雖然表達出了創新和開放很重要&#xff0c;體現了現代化&#xf…