




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
多核辦理器Linux的進度綁定辦理器核運轉名詞CPUaffinity:中文稱作“CPU親和力”,是指在CMP架構下,能夠將一個或多個進度綁定到一個或多個辦理器上運轉。一、Linux代碼中綁定多核運轉1、假如自己寫代碼,要把進度綁定到CPU,該怎么做?能夠用sched_setaffinity函數(shù)。在Linux上,這會觸發(fā)一次系統(tǒng)調用。intsched_setaffinity(pid_tpid,unsignedintlen,unsignedlong*mask);sched_setaffinity的第一個參數(shù)是pid(進度ID),設置進度為pid的這個進度,讓它運轉在mask所設定的CPU上。假如pid的值為0,則表示指定的是目行進度,使目行進度運轉在mask所設定的那些CPU上;第二個參數(shù)cpusetsize是mask所指定的數(shù)的長度。往常設定為sizeof(cpu_set_t);假如目前pid所指定的CPU此時沒有運轉在mask所指定的隨意一個CPU上,則該指定的進度會從其余CPU上遷徙到mask的指定的一個CPU上運轉。intsched_getaffinity(pid_tpid,unsignedintlen,unsignedlong*mask);該函數(shù)獲取pid所指示的進度的CPU位掩碼,并將該掩碼返回到mask所指向的構造中,即獲取指定pid目前能夠運轉在哪些CPU上。相同,假如pid的值為0.也表示的是目行進度。voidCPU_ZERO(cpu_set_t*set)這個宏對CPU集set進行初始化,將其設置為空集。voidCPU_SET(intcpu,cpu_set_t*set)這個宏將cpu加入CPU集set中。voidCPU_CLR(intcpu,cpu_set_t*set)這個宏將cpu從CPU集set中刪除。intCPU_ISSET(intcpu,constcpu_set_t*set)假如cpu是CPU集set的一員,這個宏就返回一個非零值(true),不然就返回零false)。Example:我是在一個虛構機上運轉的程序,機器CPU是雙核的,我設置虛構機模擬四核。在linux上履行top指令看結果,點擊“1”查察每個CPU核的運轉狀況。/*Shorttestprogramtotestsched_setaffinity(whichsetstheaffinityofprocessestoprocessors).Compile:gccsched_setaffinity_test.c*-osched_setaffinity_test.o-lmUsage:./sched_setaffinity_test.oOpena"top"-windowatthesametimeandseeallthework*beingdoneonCPU0firstandafterashortwaitonCPU1,2,3.Repeatwithdifferentnumberstomakesure,itisnotacoincidence.*/#include<stdio.h>#include<math.h>#include<sched.h>doublewaste_time(longn){doubleres=0;longi=0;while(i<n*200000){i++;res+=sqrt(i);}returnres;}intmain(intargc,char**argv){unsignedlongmask=1;/*二進制1,processor0*//*bindprocesstoprocessor0*/if(sched_setaffinity(0,sizeof(mask),&mask)<0){perror("sched_setaffinity");}/*wastesometimesotheworkisvisiblewith"top"*/printf("result:%f\n",waste_time(2000));mask=2;/*二進制10,processswitchestoprocessor1now*/if(sched_setaffinity(0,sizeof(mask),&mask)<0){perror("sched_setaffinity");}/*wastesomemoretimetoseetheprocessorswitch*/printf("result:%f\n",waste_time(2000));mask=4;/*二進制100,processor2*//*bindprocesstoprocessor2*/if(sched_setaffinity(0,sizeof(mask),&mask)<0){perror("sched_setaffinity");}/*wastesometimesotheworkisvisiblewith"top"*/printf("result:%f\n",waste_time(2000));mask=8;/*二進制1000,processswitchestoprocessor3now*/if(sched_setaffinity(0,sizeof(mask),&mask)<0){perror("sched_setaffinity");}/*wastesomemoretimetoseetheprocessorswitch*/printf("result:%f\n",waste_time(2000));}2、運轉結果圖2-1:圖中顯示編譯及履行一個使用“CPU親和力”的程序。圖2-2能夠看見CPU0已在履行程序(CPU達到100.0%?有必需嗎),第一段程序的結果還未出來。圖2-3能夠看見CPU1已在履行程序,第一段程序的結果已經顯示(圖片中顯示了上一次履行的結果,由于截圖比較慢,履行了3次^-^),CPU1履行的結果還未顯示出來。圖2-4:能夠看見CPU2已在履行程序,第二段程序(CPU1履行)的結果已經顯示,CPU2履行的程序結果還未出來。圖2-5::CPU3再履行程序。圖2-6:結果已經顯示,CPU恢復到履行以前的狀態(tài)二、多進度(在兩個核上各自運轉一個進度)1、代碼以下/*Shorttestprogramtotestparallel_setaffinity_test.c(whichsetstheaffinityofprocessestoprocessors).Compile:gccparallel_setaffinity_test.c-oparallel_setaffinity_test.o-lmUsage:./parallel_setaffinity_test.o*Opena"top"-windowatthesametimeandseealltheworkbeingdoneonCPU0firstandafterashortwaitonCPU1.Repeatwithdifferentnumberstomakesure,itisnotacoincidence.*/#include<stdlib.h>#include<stdio.h>#include<sys/types.h>#include<sys/sysinfo.h>#include<unistd.h>#include<string.h>#include<math.h>#include<sched.h>doublewaste_time(longn){doubleres=0;longi=0;while(i<n*200000){i++;res+=sqrt(i);}returnres;}intmain(){charbuf[100];pid_tcld_pid;intfd;intstatus;unsignedlongmask=0;strcpy(buf,"Thisisparentprocesswrite!\n");if((cld_pid=fork())==0){strcpy(buf,"Thisischildprocesswrite!\n");printf("Thisischildprocess!\n");printf("MyPID(child)is%d\n",getpid());printf("MyPID(child)is%d\n",getppid());mask=1;/*二進制1,processor0*//*bindprocesstoprocessor0*/if(sched_setaffinity(0,sizeof(mask),&mask)<0){perror("sched_setaffinity");}/*wastesometimesotheworkisvisiblewith"top"*/printf("result:%f.\n",waste_time(2000));write(fd,buf,strlen(buf));close(fd);exit(0);}else{printf("Thisisparentprocess!\n");printf("MyPID(parent)is%d.\n",getpid());printf("MychildPIDis%d.\n",cld_pid);mask=2;/*二進制10,processswitchestoprocessor1now*/if(sched_setaffinity(0,sizeof(mask),&mask)<0){perror("sched_setaffinity");}/*wastesomemoretimetoseetheprocessorswitch*/printf("result:%f.\n",waste_time(2000));write(fd,buf,strlen(buf));close(fd);}wait(&status);return0;}2、運轉結果圖3-1:圖中顯示編譯及履行一個使用“CPU親和力”的多進度程序,雙核(虛構四核太慢)。圖3-2:,父子進度并發(fā)履行,父進度在CPU1上運轉,子進度運轉在CPU0,能夠看出兩個辦理器目前都在運轉程序。圖3-3:結果已經顯示,CPU0和CPU1都恢復到履行以前的狀態(tài)附錄1、Processoraffinityisamodificationofthenativecentralqueueschedulingalgorithminasymmetricmultiprocessingoperatingsystem.Eachtask(beitprocessorthread)inthequeuehasatagindicatingitspreferred/kinprocessor.Atallocationtime,eachtaskisallocatedtoitskinprocessorinpreferencetoothers.Processoraffinitytakesadvantageofthefactthatsomeremnantsofaprocessmayremaininoneprocessor'sstate(inparticular,initscache)fromthelasttimetheprocessran.Schedulingittorunonthesameprocessorthenexttimecouldresultintheprocess'srunningmoreefficientlybyreducingperformance-degradingsituationssuchascachemisses.Apracticalexamplemightberunningmultipleinstancesofanapplicationwhichdoesnotusemultiplethreads,suchassomegraphics-renderingsoftware.Overallsystemefficiencyincreases.Schedulingalgorithmimplementationsvaryinadherencetoprocessoraffinity.Undercertaincircumstancessomeimplementationswillallowatasktochangetoanotherprocessorifthisisdeemedtobemostefficient.Thismaybethecaseiftwoprocessor-intensivetasks(A&B)haveaffinitytooneprocessorwhileanotherprocessorliesunused.ManyalgorithmswouldshifttaskBtothesecondprocessorinordertomaximizeprocessoruse.TaskBwouldthenacquireaffinitywiththesecondprocessorwhiletaskAwouldcontinuetohaveaffinitywiththeoriginalprocessor.Processoraffinitycaneffectivelyreducecacheproblemsbutitdoesnotcurbthepersistentload-balancingproblem.[1]Further,processoraffinitybecomesmorecomplicatedinsystemswithnon-uniformarchitectures.Forexample,asystemwithtwodual-corehyper-threadedCPUspresentsachallengetoaschedulingalgorithm.ThereiscompleteaffinitybetweentwovirtualCPUsimplementedonthesamecoreviahyper-threading,partialaffinitybetweentwocoresonthesamephysicalchip(asthecoressharesome,butnotall,cache),andnoaffinitybetweenseparatephysicalchips.Asotherresourcesarealsoshared,processoraffinityalonecannotbeusedasthebasisforCPUdispatching.Ifaprocesshasrecentlyrunononevirtualhyper-threadedCPUinagivencore,andthatvirtualCPUiscurrentlybusybutitspartnerisnot,cacheaffinitywouldsuggestthattheprocessshouldbedispatchedtotheidlepartner.However,thetwovirtualCPUscompeteforessentiallyallcomputing,cache,andmemoryresources.ItwouldtypicallybemoreefficientinthiscasetodispatchtheprocesstoadifferentcoreorCPUifoneisavailable.Thiswouldlikelyincurapenaltywhenprocessrepopulatesthecache,butoverallperformancewouldlikelybehigherastheprocesswouldnothavetocompeteforresourceswithintheCPU.OnLinuxtheCPUaffinityofaprocessmightbealteredwiththetaskset(1)program.[2]OnSGIsystems,dplacebindsaprocesstoasetofCPUs.[3]NetBSD5.0,FreeBSD7.2andlaterversionscanusepthread_setaffinity_npandpthread_getaffinity_np.[4]InNetBSD,thepsrsetutility[5]tosetathread'saffinitytoacertainCPUset.InFreeBSD,cpuset[6]utilityisusedtocreateCPUsetsandtoassignprocessestothesesets.OnWindowsNT,threadandprocessCPUaffinitiescanbesetseparatelybyusingSetThreadAffinityMask[7]andSetProcessAffinityMask[8]APIcallsorviatheTaskManagerinterface(forprocessaffinityonly).MacOSXexposesanaffinityAPIthatprovideshintstothekernelhowtoschedulethreadsaccordingtoaffinitysets.2、sched_setaffinity,sched_getaffinity-setandgetaprocess'sCPUaffinitymaskSYNOPSIS#include<sched.h>intsched_setaffinity(pid_tpid,unsignedintlen,unsignedlong*mask);intsched_getaffinity(pid_tpid,unsignedintlen,unsignedlong*mask);DESCRIPTIONsched_setaffinitysetstheCPUaffinitymaskoftheprocessdenotedbypid.Ifpidiszero,thenthecurrentprocessisused.Theaffinitymaskisrepresentedbythebitmaskstoredinmask.Theleastsignificantbitcorrespondstothefirstlogicalprocessornumberonthesystem,whilethemostsignificantbitcorrespondstothelastlogicalprocessornumberonthesystem.AsetbitcorrespondstoalegallyschedulableCPUwhileanunsetbitcorrespondstoanillegallyschedulableCPU.Inotherwords,aprocessisboundtoandwillonlyrunonprocessorswhosecorrespondingbitisset.Usually,allbitsinthemaskareset.Theargumentlenisthelengthofthedatapointedtobymask.Normallythisisthesizeofawordonthesystem.ForcompatibilitywithfutureversionsoftheLinuxkernel,sincethissizecanchange,thebitmasksuppliedmustbeatleastaslargeastheaffinitymaskstoredinthekernel.Thefunctionsched_getaffinitywritesintothepointersuppliedbymaskthatissizelentheaffinitymaskofprocesspid.Ifpidiszero,thenthemaskofthecurrentprocessisreturned.RETURNVALUEOnsuccess,sched_setaffinityandsched_getaffinitybothreturn0.Onerror,-1isreturned,anderrnoissetappropriately.ERRORSEFAULTAsuppliedmemoryaddresswasinvalid.ESRCHTheprocesswhoseIDispidcouldnotbefound.EPERMThecallingprocessdoesnothaveappropriateprivileges.Theprocesscallingsched_setaffinityneedsaneffectiveuidequaltotheeuidoruidoftheprocessidentifiedbypid,oritmustpossesstheCAP_SYS_NICEcapability.EINVALTheaffinitybitmaskmaskcontainsnoprocessorsthatarephysicallyonthesystemorthelengthlenissmallerthanthesizeoftheaffinitymaskusedbythekernel.HISTORYTheaffinitysyscallswereintroducedinLinuxkernel2.5.8.Thelibrarycallswereintroducedinglibc2.3,andarestillinglibc2.3.2.Laterglibc2.3.2developmentversionschangedthisinterfacetoonewithoutthelenfield,andstilllaterversionsrevertedagain.Theglibcprototypeisnow/*SettheCPUaffinityforatask*/externintsched_setaffinity(pid_tpid,size_tcpusetsize,constcpu_set_t*cpuset);/*GettheCPUaffinityforatask*/externintsched_getaffinity(pid_tpid,3、TASKSET(1)
size_tcpusetsize,cpu_set_t*cpuset);LinuxUser’sManualTASKSET(1)NAMEtaskset-retrieveorsetaprocesses’sCPUaffinitySYNOPSIStaskset[options][mask|list][pid|command[arg]...]DESCRIPTIONtasksetisusedtosetorretrievetheCPUaffinityofarunningpro-cessgivenitsPIDortolaunchanewCOMMANDwithagivenCPUaffin-ity.CPUaffinityisaschedulerpropertythat"bonds"aprocesstoagivensetofCPUsonthesystem.TheLinuxschedulerwillhonorthegivenCPUaffinityandtheprocesswillnotrunonanyotherCPUs.NotethattheLinuxscheduleralsosupportsnaturalCPUaffinity:theschedulerattemptstokeepprocessesonthesameCPUaslongaspracti-calforperformancereasons.Therefore,forcingaspecificCPUaffin-ityisusefulonlyincertainapplications.TheCPUaffinityisrepresentedasabitmask,withthelowestorderbitcorrespondingtothefirstlogicalCPUandthehighestorderbitcorre-spondingtothelastlogicalCPU.NotallCPUsmayexistonagivensystembutamaskmayspecifymoreCPUsthanarepresent.AretrievedmaskwillreflectonlythebitsthatcorrespondtoCPUsphysicallyonthesystem.Ifaninvalidmaskisgiven(i.e.,onethatcorrespondstonovalidCPUsonthecurrentsystem)anerrorisreturned.Themasksaretypicallygiveninhexadec
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 員工合同履約協(xié)議書范本
- 模板勞務承包合同協(xié)議
- 快運物流合作合同協(xié)議
- 咨詢設計服務合同協(xié)議
- 毛衣縫合加工合同協(xié)議
- 向政府購買土地合同協(xié)議
- 吵架糾紛和解協(xié)議書范本
- 商場租賃合同安全管理協(xié)議版
- 商家聯(lián)盟合作協(xié)議合同
- 商場物業(yè)外包合同協(xié)議
- 遼寧省部分高中2023-2024學年高二下學期期中考試數(shù)學試題(解析版)
- 四川省南充市閬中中學校2024-2025學年高二下學期4月期中 化學試題(含答案)
- 購買機票合同協(xié)議
- 2024年陪診師考試教材相關試題及答案
- 統(tǒng)編版七年級語文下冊《第16課有為有不為》教案
- 高中部學生會職責與組織架構分析
- 質量環(huán)境職業(yè)健康安全管理體系程序文件(終稿)
- 家政服務行業(yè)的數(shù)字化轉型及創(chuàng)新服務模式研究
- 鎮(zhèn)掃黑除惡培訓
- IDC基礎知識培訓課件
- 第三類醫(yī)療器械崗前培訓
評論
0/150
提交評論