简体   繁体   English

XV6:ptable初始化

[英]XV6: ptable initialization

I'm talking about: 我在说:

struct {
struct spinlock lock;
struct proc proc[NPROC];
} ptable;

which resides in proc.c file. 它位于proc.c文件中。

Can someone please explain where it is initialized? 有人可以解释一下它的初始化位置吗? Because, in proc.c I've never seen something (process) being added to it. 因为,在proc.c中,我从未见过添加某些东西(进程)。

To be more precise, let's say I'm looking at the scheduler code: 更确切地说,假设我正在查看调度程序代码:

void
scheduler(void)
{
 struct proc *p;
 for(;;){
 // Enable interrupts on this processor.
 sti();
 // Loop over process table looking for process to run.
 acquire(&ptable.lock);
 for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
  if(p−>state != RUNNABLE)
  continue;
  // Switch to chosen process. It is the process’s job
  // to release ptable.lock and then reacquire it
  // before jumping back to us.
  proc = p;
  switchuvm(p);
  p−>state = RUNNING;
  swtch(&cpu−>scheduler, proc−>context);
  switchkvm();
  // Process is done running for now.
  // It should have changed its p−>state before coming back.
  proc = 0;
  }
 release(&ptable.lock);
 }
}

In: 在:

for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){

you can see that we are looping thorough each process in ptable. 你可以看到我们正在循环遍历ptable中的每个进程。 My question is, how did they get there? 我的问题是,他们是如何到达那里的? Thanks! 谢谢!

It is initialised. 它被初始化了。

struct {
struct spinlock lock;
struct proc proc[NPROC];
} ptable;

the above code defines a struct (with no name) and initialises ptable as one struct of this type. 上面的代码定义了一个struct(没有名称),并将ptable初始化为此类型的一个结构。 maybe you are confusing with this syntax: 也许你对这种语法感到困惑:

struct ptable {
struct spinlock lock;
struct proc proc[NPROC];
};

here we are only defining a struct name ptable and there are no initialisations. 这里我们只定义一个结构名称ptable ,并且没有初始化。

You won't find the initialization in xv6's code. 你不会在xv6的代码中找到初始化。 Here's why. 这就是原因。

C initializes proc's int and enum variables to 0. When ptable is implemented, struct proc proc[NPROC]; C将proc的int和enum变量初始化为0.当ptable实现时, struct proc proc[NPROC]; creates an array of 64 processes whose fields are initialized to 0 by the language. 创建一个包含64个进程的数组,其字段由语言初始化为0。 0 happens to be the value of the UNUSED enumeration. 0恰好是UNUSED枚举的值。

allocproc loops through ptable.proc looking for state=UNUSED, then initializes the first one it finds to all the needed values. allocproc通过ptable.proc循环查找state = UNUSED,然后将找到的第一个初始化为所有需要的值。 So there's no need to explicitly initialize the structures in the array. 因此,无需显式初始化数组中的结构。

struct {
    struct spinlock lock;
    struct proc proc[NPROC];
}ptable;

It's allocated on the stack and initialized automatically. 它被分配在堆栈上并自动初始化。 The trick here is that it's written in the GCC way, also called anonymous struct. 这里的技巧是它以GCC方式编写,也称为匿名结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM