Domanda

So imagine I have code similar to the following:

var obj = new object();
lock (obj)
{
    while (true);
}

Since the loop will run forever, and since the loop is in a critical section:

Will this take up all of the processor's time, never yielding to another thread? I believe once a processor is in a critical section it cannot be interrupted until it leaves the critical section, so that the operations in the lock are atomic.

Could this technique be used to guarantee that your application always has a core to run on, and is never waiting?

È stato utile?

Soluzione

I believe once a processor is in a critical section it cannot be interrupted until it leaves the critical section, so that the operations in the lock are atomic

No, at the operating system level, the thread will be suspended and another thread (from another process or not) will be executed instead. The operating system scheduler is in charge of assigning CPU time to the various threads executing in the system, depending on their state and priority.

See MSDN (especially multitasking and scheduling chapters).

Also, lock doesn't mean atomic. It just means no other thread can run the same piece of code at the same time.

Altri suggerimenti

The thread will be busy forever. However this has nothing to do with thread scheduling and interruption. If it was possible to prevent a thread from being descheduled from user mode you could easily kill an entire system from an unprivileged process.

The correspondence of threads to CPU cores is by default automatically managed. You cannot reserve a core. This is not necessary either.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top