MIT 6.s081 Lab1 素数筛

该文描述了一个使用管道实现并发版本的素数筛程序。程序基于DougMcIlroy的构思,通过创建管道和进程来高效筛选素数。每个进程会检查并传递非素数给下一个进程,直到所有35以下的数字处理完毕。程序在读取管道关闭时结束,并确保所有子进程都已终止。
摘要由CSDN通过智能技术生成

文章目录

Question

Write a concurrent version of prime sieve using pipes. This idea is due to Doug McIlroy, inventor of Unix pipes. The picture halfway down this page and the surrounding text explain how to do it. Your solution should be in the file user/primes.c.
使用管道写一个并发版本的素数筛。
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.

Solution

void prime(int p[]){
    
    int c[2];
    int ans;    
    if(!read(p[0],&ans,4))
        exit(0);    
    printf("prime %d\n",ans);
    pipe(c);
    if(fork()==0){
        close(p[0]);
        close(c[1]);
        prime(c);
    }
    else{
        close(c[0]);
        int num;
        while(read(p[0],&num,4)){            
            if(num%ans!=0)
                write(c[1],&num,4);
        }
        close(p[0]);
        close(c[1]);
        wait((int *) 0);
    }
}

int
main(int argc, char *argv[])
{
  int p[2];
  pipe(p);
  for(int i=2;i<=35;i++){
    int n=i;
    write(p[1],&n,4);
  }
  close(p[1]);
  prime(p);
  exit(0);
}

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值