2014-02-12 36 views
-2

我正在编写一个模拟循环式cpu调度器的程序。在timestamp(命令行中的可变输入)时间单位数之后,调度程序应该将该进程移至队列底部并从下一个节点继续。什么使用,而不是模数?

我在尝试计算当我处于循环结束时遇到了问题,我首先尝试了模数,但是我意识到这很糟糕。然后,我尝试使用文字计算,甚至投掷浮法转换,但它仍然无法正常工作。当工作属性为0时,该陈述是真实的,并且在所有其他工作值上都是错误的。

我曾尝试:

if ((queue->worked % timestamp) != 0) 
if ((queue->worked - (timestamp * (queue->worked/timestamp))) == 0) 
if ((float) (queue->worked - (float) (timestamp * (float) (queue->worked/timestamp))) == 0) 

我也想知道是否有这样做,这样我就可以完全避免了模数的更好的方法。

下面是一些相关的代码:

struct node { 
    double process_id; 
    int arrival_time; 
    int cpu_time; 
    int worked; 
    struct node *nextElement; 
}; 

void round_robin(nodeptr firstNode, int timestamp) { 
    nodeptr queue = firstNode; 

    if ((queue->worked % timestamp) == 0) { 
     queue->worked++; 
     current_time++; 
    } 
    else { 
     tmpptr = queue; 
     queue = queue->nextElement; 
     add_to_bottom(tmpptr, queue); 
    } 
} 

下面是一组样品。这些是由主函数读入的文本文件中的行,并存储为链接的节点列表。

2001 0 20 
2002 1 10 
2005 2 15 
2007 3 4 

其中列表示进程ID,到达时间和进程计算所需的时间(以毫秒为单位)。

的指针到第一节点(处理2001)被传递给函数,以及这是作为参数传递的整数(./main 10)

在列表中的函数迭代并模拟一个圆知更鸟风格cpu调度程序。

循序渐进: 所以,如果我的时间戳输入10:(输出并不重要,现在)

Process 2001 should calculate for 10 milliseconds, then get send to the back of the list. 
Process 2002 will calculate for 10 and finish. 
Process 2005 will calculate for 10 milliseconds, get send to the back. 
Process 2007 will calculate for 4 and be done. 
Process 2001 was went to the back and now runs for 10 more and finishes. 
Process 2005 calculates for the remaining 5 and the program is now done. 

编辑:

我加一个printf,上面写着 “!如果\ n”在if和else中说“Else!\ n”,如果有一次(工作初始化为0),则打印输出,然后在该节点运行的其他时间输出。它只输入if为零值,在工作增加后它不会再次进入,并陷入将第一个过程结束的无限循环。

If! 
Else! 
If! 
Else! 
If! 
Else! 
If! 
Else! 
Else! 
Else! 
Else! 
...until it eventually segfaults after about 900 lines 
+12

*我首先尝试了模量,但是我意识到这很糟糕。* - 为什么它“不好”?请定义“没有工作”。 –

+0

@EdS。根据整数的定义,模数命令在所有语言中的工作方式都不相同。所有的陈述在工作属性为0时计算为真,在所有其他工作值中为假。 – xjsc16x

+0

为什么不'if(queue-> working!= timestamp)...'? –

回答

1

%在C中不是模量而是余数。如果您不知道它在做什么,请不要在签名类型如int上使用它。如果您将int成员更改为unsigned,或许您的担心会停止。在unsigned你有一个保证a % b总是落在0 .. b-1范围内。