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

來源:互聯網
上載者:User
#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中可以清楚的看到。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.