[comp.os.mach] Context switch of threads vs tasks

manu@portia.Stanford.EDU (Manu Thapar) (10/18/89)

Should the context swith time for threads be less than the
context switch time for tasks in Mach ?

Some time back I used the following program to measure the
context switch time for threads and tasks. The program uses
locks to force context switches.

The same program was used to measure the context switch time
for threads and tasks.

To measure the CS time for threads, the program was compiled
with the "threads library" i.e. "cc locks.c -lthreads -lmach".

To measure the CS time for tasks, the program was compiled
with the "task library" i.e. "cc locks.c -ltask_threads -lmach".

The loop forces 100,000 (50,000 x 2) context switches and takes 
around 90 sec to complete for BOTH -- threads as well as tasks.
This results in the context switch time for threads and tasks being
the same -- around 900 micro secs.
The measurements were done on a VAX8350.

I presume each thread has its own 'proc' structure and user 
structure and the context switch is done by swapping the PCB's 
for the threads. Is this  done by swtch() in locore.c as
it is done in Unix ?

I had thought (seems wrongly) that one of the reasons threads were 
considered "lightweight" was that the context switch time between 
related threads was less than between related tasks.

Comments ?

Manu.

----------------------------------------

#include <stdio.h>
#include <cthreads.h>

#define NUM_LOOP 50000

cthread_t 	new_thread;
mutex_t 	lock_1, lock_2;

/* the initialization is done by the following function */

init()
{
    cthread_init();
    lock_1 = mutex_alloc();
    lock_2 = mutex_alloc();
}

/*
*  This function resumes the other thread blocked on that threads 
*  lock and then blocks on its own lock util it is resumed by the 
*  the other thread. This function may be used to measure the 
*  context switch time for threads  when there is only one CPU in 
*  the system. 
*/

flip_locks()
{
    mutex_t 	my_lock, his_lock;
    int		i;
    cthread_t 	my_id;
    
    my_id = cthread_self();
    if (my_id != new_thread)
    {
	my_lock = lock_1;
	his_lock = lock_2;
    }
    else
    {
	my_lock = lock_2;
	his_lock = lock_1;
    }
    for (i=0; i<NUM_LOOP; i++)
    {
	mutex_lock(my_lock);
	mutex_unlock(his_lock);
    }
}
    
    

main()
{
    init();
    new_thread = cthread_fork(flip_locks);
    flip_locks();
}