Linux :多處理器遇到實時進程和普通進程的程序設計
get_thread_info(thread_index);
long num = 0;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 5000000; j++)
{
// 沒什么意義,純粹是模擬 CPU 密集計算。
float f1 = ((i+1) * 345.45) * 12.3 * 45.6 / 78.9 / ((j+1) * 4567.89);
float f2 = (i+1) * 12.3 * 45.6 / 78.9 * (j+1);
float f3 = f1 / f2;
}
// 打印計數信息,為了能看到某個線程正在執行
printf("thread_index %d: num = %ld ", thread_index, num++);
}
// 線程執行結束
printf("thread_index %d: exit ", thread_index);
return 0;
}
void main(void)
{
// 一共創建四個線程:0和1-實時線程,2和3-普通線程(非實時)
int thread_num = 4;
// 分配的線程索引號,會傳遞給線程參數
int index[4] = {1, 2, 3, 4};
// 用來保存 4 個線程的 id 號
pthread_t ppid[4];
// 用來設置 2 個實時線程的屬性:調度策略和優先級
pthread_attr_t attr[2];
struct sched_param param[2];
// 實時線程,必須由 root 用戶才能創建
if (0 != getuid())
{
printf("Please run as root ");
exit(0);
}
// 創建 4 個線程
for (int i = 0; i < thread_num; i++)
{
if (i <= 1) // 前2個創建實時線程
{
// 初始化線程屬性
pthread_attr_init(&attr[i]);
// 設置調度策略為:SCHED_FIFO
pthread_attr_setschedpolicy(&attr[i], SCHED_FIFO);
// 設置優先級為 51,52。
param[i].__sched_priority = 51 + i;
pthread_attr_setschedparam(&attr[i], &param[i]);
// 設置線程屬性:不要繼承 main 線程的調度策略和優先級。
pthread_attr_setinheritsched(&attr[i], PTHREAD_EXPLICIT_SCHED);
// 創建線程
pthread_create(&ppid[i], &attr[i],(void *)thread_routine, (void *)&index[i]);
}
else // 后兩個創建普通線程
{
pthread_create(&ppid[i], 0, (void *)thread_routine, (void *)&index[i]);
}
}
// 等待 4 個線程執行結束
for (int i = 0; i < 4; i++)
pthread_join(ppid[i], 0);
for (int i = 0; i < 2; i++)
pthread_attr_destroy(&attr[i]);
}
編譯成可執行程序的指令:
gcc -o test test.c -lpthread
腦殘測試開始
首先說一下預期結果,如果沒有預期結果,那其他任何問題都壓根不用談了。
一共有 4 個線程:
線程索引號 1和2:是實時線程(調度策略是 SCHED_FIFO,優先級是 51,52);
線程索引號 3和4:是普通線程(調度策略是 SCHED_OTHER, 優先級是 0);
我的測試環境是:Ubuntu16.04,是一臺安裝在 Windows10 上面的虛擬機。
我期望的結果是:
首先打印 1 號和 2 號這兩個線程的信息,因為它倆是實時任務,需要優先被調度;
1 號線程的優先級是 51,小于 2 號線程的優先級 52,因此應該是 2 號線程結束之后,才輪到 1 號線程執行;
3 號和 4 號線程是普通進程,它倆需要等到 1 號和 2 號線程全部執行結束之后才開始執行,并且 3 號和 4 號線程應該是交替執行,因為它倆的調度策略和優先級都是一樣的。
我滿懷希望的在工作電腦中測試,打印結果如下:
====> thread_index = 4
thread_index 4: SCHED_OTHER
thread_index 4: priority = 0
====> thread_index = 1
thread_index 1: SCHED_FIFO
thread_index 1: priority = 51
====> thread_index = 2
thread_index 2: SCHED_FIFO
thread_index 2: priority = 52
thread_index 2: num = 0
thread_index 4: num = 0
====> thread_index = 3
thread_index 3: SCHED_OTHER
thread_index 3: priority = 0
thread_index 1: num = 0
thread_index 2: num = 1
thread_index 4: num = 1
thread_index 3: num = 0
thread_index 1: num = 1
thread_index 2: num = 2
thread_index 4: num = 2
thread_index 3: num = 1
后面打印內容不用輸出了,因為前面已經出現了問題。
請輸入評論內容...
請輸入評論/評論長度6~500個字
最新活動更多
- 1 AI狂歡遇上油價破百,全球股市還能漲多久? | 產聯看全球
- 2 OpenAI深夜王炸!ChatGPT Images 2.0實測:中文穩、細節炸,設計師慌了
- 3 6000億美元估值錨定:字節跳動的“去單一化”突圍與估值重構
- 4 Tesla AI5芯片最新進展總結
- 5 連夜測了一波DeepSeek-V4,我發現它可能只剩“審美”這個短板了
- 6 熱點丨AI“瑜亮之爭”:既生OpenClaw,何生Hermes?
- 7 AI界的殺豬盤:9秒刪庫跑路,全員被封號,還繼續扣錢!
- 8 2026,人形機器人只贏了面子
- 9 DeepSeek降價90%:價格屠夫不是身份,是戰略
- 10 AI Infra產業鏈卡在哪里了?


分享













