Linux 2.6.23开始使用CFS(complete fair schedule),线程Priority不再有效

#include  < glib.h >
#include 
< stdio.h >

static  gpointer thread_func(gpointer data)
{
    guint64 result 
=   0 ;
    guint64 i 
=   0 ;

    
for  (i  =   0 ; i  <   100000000 ; i ++ ) {
        result 
+=  i;
    }

    g_message(
" Add finished. The result is: %lld " , result);
}

int  main( int  argc,  char   * argv[])
{
    GThread 
* handle  =  NULL;
    GTimeVal start_time, end_time;
    gdouble stime, etime, time_usage;
    
    g_thread_init(NULL);

    g_get_current_time(
& start_time);

    g_message(
" Create low priority thread now. " );
    handle 
=  g_thread_create_full((GThreadFunc)thread_func, NULL,  0 , TRUE, TRUE, G_THREAD_PRIORITY_LOW, NULL);
    
if  (handle  ==  NULL) {
        g_message(
" Create thread failed, quit. " );
        
return   1 ;
    }

    g_thread_join(handle);
    g_get_current_time(
& end_time);

    stime 
=  start_time.tv_sec  +  (gdouble)start_time.tv_usec  /   1000000 ;
    etime 
=  end_time.tv_sec  +  (gdouble)end_time.tv_usec  /   1000000 ;
    time_usage 
=  (etime  -  stime)  *   1000 ;

    g_message(
" Time elapsed: %.2f ms " , time_usage);
    
return   0 ;
}
 

 可以将这个代码中的线程优先级改成HIGH或URGENT,然后生成两个可执行程序,运行会发现两个程序运行的时间差不多,将系统CPU占用调高,再测试也是一样。或者写一个脚本,同时运行两个程序,也是一样。


这说明现在在pthread中设定线程的priority已经没有效果了。查阅了资料知道,这是因为现在linux默认的调度策略是CFS,完全公平的调度策略,完全根据每个进程消耗的cpu时间来决定下次由哪个进程被调度。如果要改变这种调度策略,那可以使用linux提供的FIFO或RR(round robin)这种类型的策略,这种类型对应到kernel中,是名为realtime的策略,具体在内核sched.c中可以清楚的看到。

你可能感兴趣的:(schedule)