Why do we need to acquire the current thread's lock before context switching?

Dheeraj Kandula dkandula at gmail.com
Thu Sep 12 10:48:44 UTC 2013


Thanks a lot Alfred for the clarification. So is the td_lock granular i.e.
one separate lock for each thread but also used for protecting the
scheduler variables or is it just one lock used by all threads and the
scheduler as well. I will anyway go through the code that you suggested but
just wanted to have a deeper understanding before I go about hunting in the
code.

Dheeraj


On Thu, Sep 12, 2013 at 3:10 AM, Alfred Perlstein <bright at mu.org> wrote:

> On 9/11/13 2:39 PM, Dheeraj Kandula wrote:
>
>> Hey All,
>>
>> When the current thread is being context switched with a newly selected
>> thread, why is the current thread's lock acquired before context switch –
>> mi_switch() is invoked after thread_lock(td) is called. A thread at any
>> time runs only on one of the cores of a CPU. Hence when it is being
>> context
>> switched it is added either to the real time runq or the timeshare runq or
>> the idle runq with the lock still held or it is added to the sleep queue
>> or
>> the blocked queue. So this happens atomically even without the lock. Isn't
>> it? Am I missing something here? I don't see any contention for the thread
>> in order to demand a lock for the thread which will basically protect the
>> contents of the thread structure for the thread.
>>
>> Dheeraj
>>
>>
> The thread lock also happens to protect various scheduler variables:
>
>         struct mtx      *volatile td_lock; /* replaces sched lock */
>
> see sys/kern/sched_ule.c on how the thread lock td_lock is changed
> depending on what the thread is doing.
>
> --
> Alfred Perlstein
>
>


More information about the freebsd-arch mailing list