English 中文(简体)
如何造成拖延
原标题:how to generate a delay

i m new to kernel programming and i m trying to understand some basics of OS. I am trying to generate a delay using a technique which i ve implemented successfully in a 20Mhz microcontroller. I know this is a totally different environment as i m using linux centOS in my 2 GHz Core 2 duo processor. I ve tried the following code but i m not getting a delay.

#include<linux/kernel.h>
#include<linux/module.h>

int init_module (void)
{
        unsigned long int i, j, k, l;

        for (l = 0; l < 100; l ++)
        {
                for (i = 0; i < 10000; i ++)
                {
                        for ( j = 0; j < 10000; j ++)
                        {
                                for ( k = 0; k < 10000; k ++);
                        }
                }
        }

        printk ("
hello
");

        return 0;
}

void cleanup_module (void)
{
        printk ("bye");
}

When i dmesg after inserting the module as quickly as possile for me, the string "hello" is already there. If my calculation is right, the above code should give me atleast 10 seconds delay. Why is it not working? Is there anything related to threading? How could a 20 Ghz processor execute the above code instantly without any noticable delay?

问题回答

The compiler is optimizing your loop away since it has no side effects.

To actually get a 10 second (non-busy) delay, you can do something like this:

#include <linux/sched.h>
//...

unsigned long to = jiffies + (10 * HZ); /* current time + 10 seconds */

while (time_before(jiffies, to))
{
    schedule();
}

或更好:

#include <linux/delay.h>
//...

msleep(10 * 1000);

短期内,可使用<代码>mdelay,ndelayude<>>。

我建议你读到。 第3版第7.3章,论及信息延误问题

To answer the question directly, it s likely your compiler seeing that these loops don t do anything and "optimizing" them away.

As for this technique, what it looks like you re trying to do is use all of the processor to create a delay. While this may work, an OS should be designed to maximize processor time. This will just waste it.

我理解它是一种实验,但只是头脑。





相关问题
Silverlight, Updating the UI during processing

I have a simple silverlight multifile upload application, and i want to provide the user with some feedback, right now its only in a test phase and i dont have the webservice. Somehow i cant get the ...

Is reading from an XmlDocument object thread safe?

I was wondering if i could safely read from an XmlDocument object using SelectNodes() and SelectSingleNode() from multiple threads with no problems. MSDN says that they are not guaranteed to be ...

Terminating a thread gracefully not using TerminateThread()

My application creates a thread and that runs in the background all the time. I can only terminate the thread manually, not from within the thread callback function. At the moment I am using ...