寫了樣品C++,與10個線程運行多線程程序,每個線程設置爲高優先級和親和力。在具有16個內核的dell機器上編譯並運行此代碼,運行centos 7(Linux內核-3.10.0-229),禁用超線程。之後我跑這個代碼,在幾秒鐘內,我們的Linux機器變得反應遲鈍,因爲,如果我打開Eclipse編輯器,並保存文件或保存在vi編輯器文件中的應用程序掛起感。有趣的是,一旦我停止了這個程序/進程,那麼所有其他應用程序就會從他們離開的地方恢復。此外,如果我從這10個線程中刪除優先級,我不會看到此問題。Linux內核響應當在多個內核的多個高優先級線程運行
問題:
1)停止16個內核,6芯仍留在機器上(上述CPU使用率所示,CPU執行62.9%的用戶空間,並且是空閒37.1%有趣的是0%的CPU。在內核空間中的使用),所以理想情況下內核應該使用這6個內核來處理其他應用程序,可能是其他應用程序無法運行的原因?如何在不引入睡眠/更改優先級的情況下解決此問題?
2)想知道比線程引入睡眠/等待一個事件(其引入最小的延遲由於內核上下文開關)來實現並行其他更好的方法?
然頂部命令(top -H
):
%Cpu(s): 62.9 us, 0.0 sy, 0.0 ni, 37.1 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
1107 arun rt 0 96748 1112 932 R 99.9 0.0 0:25.78 PthreadTest
1115 arun rt 0 96748 1112 932 R 99.9 0.0 0:24.79 PthreadTest
1118 arun rt 0 96748 1112 932 R 99.9 0.0 0:22.79 PthreadTest
1120 arun rt 0 96748 1112 932 R 99.9 0.0 0:20.79 PthreadTest
1123 arun rt 0 96748 1112 932 R 99.9 0.0 0:18.79 PthreadTest
1117 arun rt 0 96748 1112 932 R 94.1 0.0 0:23.78 PthreadTest
1119 arun rt 0 96748 1112 932 R 94.1 0.0 0:21.78 PthreadTest
1122 arun rt 0 96748 1112 932 R 94.1 0.0 0:19.78 PthreadTest
1124 arun rt 0 96748 1112 932 R 94.1 0.0 0:17.78 PthreadTest
1125 arun rt 0 96748 1112 932 R 94.1 0.0 0:16.76 PthreadTest
代碼下面:
#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 10
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
while(true)
{
continue;
}
pthread_exit(NULL);
}
int main()
{
pthread_t threads[NUM_THREADS];
pthread_attr_t threads_attr[NUM_THREADS];
struct sched_param params;
params.sched_priority = sched_get_priority_max(SCHED_FIFO);
int rc;
int i;
int cpu_num = 0;
for(i=0; i < NUM_THREADS; i++){
cpu_set_t cpu;
CPU_ZERO(&cpu);
CPU_SET(cpu_num, &cpu);
cout << "main() : creating thread, " << i << "cpu_num : "<<cpu_num<<endl;
pthread_attr_init(&threads_attr[i]);
pthread_attr_setscope(&threads_attr[i], PTHREAD_SCOPE_SYSTEM);
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
sleep(1);
int ret = pthread_setaffinity_np(threads[i], sizeof(cpu_set_t), &cpu);
if(ret == 0 && CPU_ISSET(cpu_num, &cpu))
{
cout << "Thread " << i << " affinity set " <<endl;
}
ret = pthread_setschedparam(threads[i], SCHED_FIFO, ¶ms);
if(ret == 0)
{
cout << "Thread " << i << " priority set " <<endl;
}
cpu_num++;
}
// free attribute and wait for the other threads
void *status;
for(i=0; i < NUM_THREADS; i++)
{
rc = pthread_join(threads[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Main: completed thread id :" << i ;
cout << " exiting with status :" << status << endl;
}
pthread_exit(NULL);
}
編譯:
g++ -std=c++14 -g -o PthreadTest busywait.cpp -lpthread
這個問題很有趣,但出於好奇,爲什麼你在高優先級運行這個東西?具有較高優先級的CPU進食線程是完全掛起低優先級計劃的配方... –
線程總是希望CPU應該有降低的優先級,如果任何事情。 –
這臺機器有哪些CPU?你爲什麼要用GCC/linux指定'-lpthread'? (正確的標誌是'-pthread'。) –