#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中可以清楚的看到。