版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
多核辦理器Linux的進(jìn)度綁定辦理器核運(yùn)轉(zhuǎn)名詞CPUaffinity:中文稱作“CPU親和力”,是指在CMP架構(gòu)下,能夠?qū)⒁粋€(gè)或多個(gè)進(jìn)度綁定到一個(gè)或多個(gè)辦理器上運(yùn)轉(zhuǎn)。一、Linux代碼中綁定多核運(yùn)轉(zhuǎn)1、假如自己寫代碼,要把進(jìn)度綁定到CPU,該怎么做?能夠用sched_setaffinity函數(shù)。在Linux上,這會(huì)觸發(fā)一次系統(tǒng)調(diào)用。intsched_setaffinity(pid_tpid,unsignedintlen,unsignedlong*mask);sched_setaffinity的第一個(gè)參數(shù)是pid(進(jìn)度ID),設(shè)置進(jìn)度為pid的這個(gè)進(jìn)度,讓它運(yùn)轉(zhuǎn)在mask所設(shè)定的CPU上。假如pid的值為0,則表示指定的是目行進(jìn)度,使目行進(jìn)度運(yùn)轉(zhuǎn)在mask所設(shè)定的那些CPU上;第二個(gè)參數(shù)cpusetsize是mask所指定的數(shù)的長度。往常設(shè)定為sizeof(cpu_set_t);假如目前pid所指定的CPU此時(shí)沒有運(yùn)轉(zhuǎn)在mask所指定的隨意一個(gè)CPU上,則該指定的進(jìn)度會(huì)從其余CPU上遷徙到mask的指定的一個(gè)CPU上運(yùn)轉(zhuǎn)。intsched_getaffinity(pid_tpid,unsignedintlen,unsignedlong*mask);該函數(shù)獲取pid所指示的進(jìn)度的CPU位掩碼,并將該掩碼返回到mask所指向的構(gòu)造中,即獲取指定pid目前能夠運(yùn)轉(zhuǎn)在哪些CPU上。相同,假如pid的值為0.也表示的是目行進(jìn)度。voidCPU_ZERO(cpu_set_t*set)這個(gè)宏對(duì)CPU集set進(jìn)行初始化,將其設(shè)置為空集。voidCPU_SET(intcpu,cpu_set_t*set)這個(gè)宏將cpu加入CPU集set中。voidCPU_CLR(intcpu,cpu_set_t*set)這個(gè)宏將cpu從CPU集set中刪除。intCPU_ISSET(intcpu,constcpu_set_t*set)假如cpu是CPU集set的一員,這個(gè)宏就返回一個(gè)非零值(true),不然就返回零false)。Example:我是在一個(gè)虛構(gòu)機(jī)上運(yùn)轉(zhuǎn)的程序,機(jī)器CPU是雙核的,我設(shè)置虛構(gòu)機(jī)模擬四核。在linux上履行top指令看結(jié)果,點(diǎn)擊“1”查察每個(gè)CPU核的運(yùn)轉(zhuǎn)狀況。/*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;/*二進(jìn)制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;/*二進(jìn)制10,processswitchestoprocessor1now*/if(sched_setaffinity(0,sizeof(mask),&mask)<0){perror("sched_setaffinity");}/*wastesomemoretimetoseetheprocessorswitch*/printf("result:%f\n",waste_time(2000));mask=4;/*二進(jìn)制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;/*二進(jìn)制1000,processswitchestoprocessor3now*/if(sched_setaffinity(0,sizeof(mask),&mask)<0){perror("sched_setaffinity");}/*wastesomemoretimetoseetheprocessorswitch*/printf("result:%f\n",waste_time(2000));}2、運(yùn)轉(zhuǎn)結(jié)果圖2-1:圖中顯示編譯及履行一個(gè)使用“CPU親和力”的程序。圖2-2能夠看見CPU0已在履行程序(CPU達(dá)到100.0%?有必需嗎),第一段程序的結(jié)果還未出來。圖2-3能夠看見CPU1已在履行程序,第一段程序的結(jié)果已經(jīng)顯示(圖片中顯示了上一次履行的結(jié)果,由于截圖比較慢,履行了3次^-^),CPU1履行的結(jié)果還未顯示出來。圖2-4:能夠看見CPU2已在履行程序,第二段程序(CPU1履行)的結(jié)果已經(jīng)顯示,CPU2履行的程序結(jié)果還未出來。圖2-5::CPU3再履行程序。圖2-6:結(jié)果已經(jīng)顯示,CPU恢復(fù)到履行以前的狀態(tài)二、多進(jìn)度(在兩個(gè)核上各自運(yùn)轉(zhuǎn)一個(gè)進(jìn)度)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;/*二進(jìn)制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;/*二進(jìn)制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、運(yùn)轉(zhuǎn)結(jié)果圖3-1:圖中顯示編譯及履行一個(gè)使用“CPU親和力”的多進(jìn)度程序,雙核(虛構(gòu)四核太慢)。圖3-2:,父子進(jìn)度并發(fā)履行,父進(jìn)度在CPU1上運(yùn)轉(zhuǎn),子進(jìn)度運(yùn)轉(zhuǎn)在CPU0,能夠看出兩個(gè)辦理器目前都在運(yùn)轉(zhuǎn)程序。圖3-3:結(jié)果已經(jīng)顯示,CPU0和CPU1都恢復(fù)到履行以前的狀態(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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024年度成都市光伏發(fā)電項(xiàng)目投資合同
- 2024大數(shù)據(jù)分析與商業(yè)決策支持合同
- 2024不銹鋼來料加工合同
- 2024寺廟仿古建筑施工合同技術(shù)支持合同
- 2024年建筑外墻清洗維護(hù)合同
- 2024年度二手房出售交接事項(xiàng)及保修條款合同
- 2024年度設(shè)備租賃合同設(shè)備類型與租賃期限
- 2024光電子技術(shù)研發(fā)與合作合同
- 2024年度N95口罩生產(chǎn)線擴(kuò)建貸款合同
- 2024年建筑工程經(jīng)紀(jì)代理協(xié)議
- 《嬰幼兒行為觀察、記錄與評(píng)價(jià)》習(xí)題庫 (項(xiàng)目三) 0 ~ 3 歲嬰幼兒語言發(fā)展觀察、記錄與評(píng)價(jià)
- 英語漫談膠東海洋文化知到章節(jié)答案智慧樹2023年威海海洋職業(yè)學(xué)院
- 環(huán)保產(chǎn)品管理規(guī)范
- 幼兒園:我中獎(jiǎng)了(實(shí)驗(yàn)版)
- 趙學(xué)慧-老年社會(huì)工作理論與實(shí)務(wù)-教案
- 《世界主要海峽》
- 住院醫(yī)師規(guī)范化培訓(xùn)師資培訓(xùn)
- 中央企業(yè)商業(yè)秘密安全保護(hù)技術(shù)指引2015版
- 螺旋果蔬榨汁機(jī)的設(shè)計(jì)
- 《脊柱整脊方法》
- 會(huì)計(jì)與財(cái)務(wù)管理專業(yè)英語智慧樹知到答案章節(jié)測試2023年哈爾濱商業(yè)大學(xué)
評(píng)論
0/150
提交評(píng)論