문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top