interprocess.qbk 313 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510
  1. [/
  2. / Copyright (c) 2005-2012 Ion Gaztanaga
  3. /
  4. / Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. /]
  7. [library Boost.Interprocess
  8. [quickbook 1.5]
  9. [authors [Gaztanaga, Ion]]
  10. [copyright 2005-2015 Ion Gaztanaga]
  11. [id interprocess]
  12. [dirname interprocess]
  13. [purpose Interprocess communication utilities]
  14. [license
  15. Distributed under the Boost Software License, Version 1.0.
  16. (See accompanying file LICENSE_1_0.txt or copy at
  17. [@http://www.boost.org/LICENSE_1_0.txt])
  18. ]
  19. ]
  20. [section:intro Introduction]
  21. [*Boost.Interprocess] simplifies the use of common interprocess communication
  22. and synchronization mechanisms and offers a wide range of them:
  23. * Shared memory.
  24. * Memory-mapped files.
  25. * Semaphores, mutexes, condition variables and upgradable mutex types to place
  26. them in shared memory and memory mapped files.
  27. * Named versions of those synchronization objects, similar to UNIX/Windows
  28. sem_open/CreateSemaphore API.
  29. * File locking.
  30. * Relative pointers.
  31. * Message queues.
  32. [*Boost.Interprocess] also offers higher-level interprocess mechanisms to allocate
  33. dynamically portions of a shared memory or a memory mapped file (in general,
  34. to allocate portions of a fixed size memory segment). Using these mechanisms,
  35. [*Boost.Interprocess] offers useful tools to construct C++ objects, including
  36. STL-like containers, in shared memory and memory mapped files:
  37. * Dynamic creation of anonymous and named objects in a shared memory or memory
  38. mapped file.
  39. * STL-like containers compatible with shared memory/memory-mapped files.
  40. * STL-like allocators ready for shared memory/memory-mapped files implementing
  41. several memory allocation patterns (like pooling).
  42. [section:introduction_building_interprocess Building Boost.Interprocess]
  43. There is no need to compile [*Boost.Interprocess], since it's
  44. a header only library. Just include your Boost header directory in your
  45. compiler include path.
  46. [*Boost.Interprocess] depends on
  47. [@http://www.boost.org/libs/date_time/ [*Boost.DateTime]], which needs
  48. separate compilation. However, the subset used by [*Boost.Interprocess] does
  49. not need any separate compilation so the user can define `BOOST_DATE_TIME_NO_LIB`
  50. to avoid Boost from trying to automatically link the [*Boost.DateTime].
  51. In POSIX systems, [*Boost.Interprocess] uses pthread system calls to implement
  52. classes like mutexes, condition variables, etc... In some operating systems,
  53. these POSIX calls are implemented in separate libraries that are not automatically
  54. linked by the compiler. For example, in some Linux systems POSIX pthread functions
  55. are implemented in `librt.a` library, so you might need to add that library
  56. when linking an executable or shared library that uses [*Boost.Interprocess].
  57. If you obtain linking errors related to those pthread functions, please revise
  58. your system's documentation to know which library implements them.
  59. [endsect]
  60. [section:tested_compilers Tested compilers]
  61. [*Boost.Interprocess] has been tested in the following compilers/platforms:
  62. * Visual C++ >= 7.1.
  63. * GCC >= 4.1.
  64. [warning GCC < 4.3 and MSVC < 9.0 are deprecated and will be removed in the next version.]
  65. [endsect]
  66. [endsect]
  67. [section:quick_guide Quick Guide for the Impatient]
  68. [section:qg_memory_pool Using shared memory as a pool of unnamed memory blocks]
  69. You can just allocate a portion of a shared memory segment, copy the
  70. message to that buffer, send the offset of that portion of shared
  71. memory to another process, and you are done. Let's see the example:
  72. [import ../example/doc_ipc_message.cpp]
  73. [doc_ipc_message]
  74. [endsect]
  75. [section:qg_named_interprocess Creating named shared memory objects]
  76. You want to create objects in a shared memory segment, giving a string name to them so that
  77. any other process can find, use and delete them from the segment when the objects are not
  78. needed anymore. Example:
  79. [import ../example/doc_named_alloc.cpp]
  80. [doc_named_alloc]
  81. [endsect]
  82. [section:qg_offset_ptr Using an offset smart pointer for shared memory]
  83. [*Boost.Interprocess] offers offset_ptr smart pointer family
  84. as an offset pointer that stores the distance between the address of
  85. the offset pointer itself and the address of the pointed object.
  86. When offset_ptr is placed in a shared memory segment, it
  87. can point safely objects stored in the same shared
  88. memory segment, even if the segment is mapped in
  89. different base addresses in different processes.
  90. This allows placing objects with pointer members
  91. in shared memory. For example, if we want to create
  92. a linked list in shared memory:
  93. [import ../example/doc_offset_ptr.cpp]
  94. [doc_offset_ptr]
  95. To help with basic data structures, [*Boost.Interprocess] offers containers like vector,
  96. list, map, so you can avoid these manual data structures just like with standard containers.
  97. [endsect]
  98. [section:qg_interprocess_container Creating vectors in shared memory]
  99. [*Boost.Interprocess] allows creating complex objects in shared memory and memory
  100. mapped files. For example, we can construct STL-like containers in shared memory.
  101. To do this, we just need to create a special (managed) shared memory segment,
  102. declare a [*Boost.Interprocess] allocator and construct the vector in shared memory
  103. just if it was any other object.
  104. The class that allows this complex structures in shared memory is called
  105. [classref boost::interprocess::managed_shared_memory] and it's easy to use.
  106. Just execute this example without arguments:
  107. [import ../example/doc_spawn_vector.cpp]
  108. [doc_spawn_vector]
  109. The parent process will create an special shared memory class that allows easy construction
  110. of many complex data structures associated with a name. The parent process executes the same
  111. program with an additional argument so the child process opens the shared memory and uses
  112. the vector and erases it.
  113. [endsect]
  114. [section:qg_interprocess_map Creating maps in shared memory]
  115. Just like a vector, [*Boost.Interprocess] allows creating maps in
  116. shared memory and memory mapped files. The only difference is that
  117. like standard associative containers, [*Boost.Interprocess]'s map needs
  118. also the comparison functor when an allocator is passed in the constructor:
  119. [import ../example/doc_map.cpp]
  120. [doc_map]
  121. For a more advanced example including containers of containers, see the section
  122. [link interprocess.allocators_containers.containers_explained.containers_of_containers Containers of containers].
  123. [endsect]
  124. [endsect]
  125. [section:some_basic_explanations Some basic explanations]
  126. [section:processes_and_threads Processes And Threads]
  127. [*Boost.Interprocess] does not work only with processes but also with threads.
  128. [*Boost.Interprocess] synchronization mechanisms can synchronize threads
  129. from different processes, but also threads from the same process.
  130. [endsect]
  131. [section:sharing_information Sharing information between processes]
  132. In the traditional programming model an operating system has multiple processes
  133. running and each process has its own address space. To share information between
  134. processes we have several alternatives:
  135. * Two processes share information using a [*file]. To access to the data, each
  136. process uses the usual file read/write mechanisms. When updating/reading
  137. a file shared between processes, we need some sort of synchronization, to
  138. protect readers from writers.
  139. * Two processes share information that resides in the [*kernel] of the operating
  140. system. This is the case, for example, of traditional message queues. The
  141. synchronization is guaranteed by the operating system kernel.
  142. * Two processes can share a [*memory] region. This is the case of classical
  143. shared memory or memory mapped files. Once the processes set up the
  144. memory region, the processes can read/write the data like any
  145. other memory segment without calling the operating system's kernel. This
  146. also requires some kind of manual synchronization between processes.
  147. [endsect]
  148. [section:persistence Persistence Of Interprocess Mechanisms]
  149. One of the biggest issues with interprocess communication mechanisms is the lifetime
  150. of the interprocess communication mechanism.
  151. It's important to know when an interprocess communication mechanism disappears from the
  152. system. In [*Boost.Interprocess], we can have 3 types of persistence:
  153. * [*Process-persistence]: The mechanism lasts until all the processes that have
  154. opened the mechanism close it, exit or crash.
  155. * [*Kernel-persistence]: The mechanism exists until the kernel of the operating
  156. system reboots or the mechanism is explicitly deleted.
  157. * [*Filesystem-persistence]: The mechanism exists until the mechanism is explicitly
  158. deleted.
  159. Some native POSIX and Windows IPC mechanisms have different persistence so it's
  160. difficult to achieve portability between Windows and POSIX native mechanisms.
  161. [*Boost.Interprocess] classes have the following persistence:
  162. [table Boost.Interprocess Persistence Table
  163. [[Mechanism] [Persistence]]
  164. [[Shared memory] [Kernel or Filesystem]]
  165. [[Memory mapped file] [Filesystem]]
  166. [[Process-shared mutex types] [Process]]
  167. [[Process-shared semaphore] [Process]]
  168. [[Process-shared condition] [Process]]
  169. [[File lock] [Process]]
  170. [[Message queue] [Kernel or Filesystem]]
  171. [[Named mutex] [Kernel or Filesystem]]
  172. [[Named semaphore] [Kernel or Filesystem]]
  173. [[Named condition] [Kernel or Filesystem]]
  174. ]
  175. As you can see, [*Boost.Interprocess] defines some mechanisms with "Kernel or Filesystem"
  176. persistence. This is because POSIX allows this possibility to native interprocess
  177. communication implementations. One could, for example, implement
  178. shared memory using memory mapped files and obtain filesystem persistence (for example,
  179. there is no proper known way to emulate kernel persistence with a user library
  180. for Windows shared memory using native shared memory,
  181. or process persistence for POSIX shared memory, so the only portable way is to
  182. define "Kernel or Filesystem" persistence).
  183. [endsect]
  184. [section:names Names Of Interprocess Mechanisms]
  185. Some interprocess mechanisms are anonymous objects created in shared memory or
  186. memory-mapped files but other interprocess mechanisms need a name or identifier
  187. so that two unrelated processes can use the same interprocess mechanism object.
  188. Examples of this are shared memory, named mutexes and named semaphores (for example,
  189. native windows CreateMutex/CreateSemaphore API family).
  190. The name used to identify an interprocess mechanism is not portable, even between
  191. UNIX systems. For this reason, [*Boost.Interprocess] limits this name to a C++ variable
  192. identifier or keyword:
  193. *Starts with a letter, lowercase or uppercase, such as a letter from a to z or from
  194. A to Z. Examples: ['Sharedmemory, sharedmemory, sHaReDmEmOrY...]
  195. *Can include letters, underscore, or digits. Examples: ['shm1, shm2and3, ShM3plus4...]
  196. [endsect]
  197. [section:constructors_destructors_and_resource_lifetime
  198. Constructors, destructors and lifetime of Interprocess named resources]
  199. Named [*Boost.Interprocess] resources (shared memory, memory mapped files,
  200. named mutexes/conditions/semaphores) have kernel or filesystem persistency.
  201. This means that even if all processes that have opened those resources
  202. end, the resource will still be accessible to be opened again and the resource
  203. can only be destructed via an explicit call to their static member `remove` function.
  204. This behavior can be easily understood, since it's the same mechanism used
  205. by functions controlling file opening/creation/erasure:
  206. [table Boost.Interprocess-Filesystem Analogy
  207. [[Named Interprocess resource] [Corresponding std file] [Corresponding POSIX operation]]
  208. [[Constructor] [std::fstream constructor][open]]
  209. [[Destructor] [std::fstream destructor] [close]]
  210. [[Member `remove`] [None. `std::remove`] [unlink]]
  211. ]
  212. Now the correspondence between POSIX and Boost.Interprocess
  213. regarding shared memory and named semaphores:
  214. [table Boost.Interprocess-POSIX shared memory
  215. [[`shared_memory_object` operation] [POSIX operation]]
  216. [[Constructor] [shm_open]]
  217. [[Destructor] [close]]
  218. [[Member `remove`] [shm_unlink]]
  219. ]
  220. [table Boost.Interprocess-POSIX named semaphore
  221. [[`named_semaphore` operation] [POSIX operation]]
  222. [[Constructor] [sem_open]]
  223. [[Destructor] [close]]
  224. [[Member `remove`] [sem_unlink]]
  225. ]
  226. The most important property is that [*destructors of named resources
  227. don't remove the resource from the system], they only liberate resources
  228. allocated by the system for use by the process for the named resource.
  229. [*To remove the resource from the system the programmer must use
  230. `remove`].
  231. [endsect]
  232. [section:permissions Permissions]
  233. Named resources offered by [*Boost.Interprocess] must cope with platform-dependant
  234. permission issues also present when creating files. If a programmer wants to
  235. shared shared memory, memory mapped files or named synchronization mechanisms
  236. (mutexes, semaphores, etc...) between users, it's necessary to specify
  237. those permissions. Sadly, traditional UNIX and Windows permissions are very
  238. different and [*Boost.Interprocess] does not try to standardize permissions,
  239. but does not ignore them.
  240. All named resource creation functions take an optional
  241. [classref boost::interprocess::permissions permissions object] that can be
  242. configured with platform-dependant permissions.
  243. Since each mechanism can be emulated through different mechanisms
  244. (a semaphore might be implement using mapped files or native semaphores)
  245. permissions types could vary when the implementation of a named resource
  246. changes (eg.: in Windows mutexes require `synchronize permissions`, but
  247. that's not the case of files).
  248. To avoid this, [*Boost.Interprocess] relies on file-like permissions,
  249. requiring file read-write-delete permissions to open named synchronization mechanisms
  250. (mutex, semaphores, etc.) and appropriate read or read-write-delete permissions for
  251. shared memory. This approach has two advantages: it's similar to the UNIX philosophy
  252. and the programmer does not need to know how the named resource is implemented.
  253. [endsect]
  254. [endsect]
  255. [section:sharedmemorybetweenprocesses Sharing memory between processes]
  256. [section:sharedmemory Shared memory]
  257. [section:shared_memory_what_is What is shared memory?]
  258. Shared memory is the fastest interprocess communication mechanism.
  259. The operating system maps a memory segment in the address space of several
  260. processes, so that several processes can read and write in that memory segment
  261. without calling operating system functions. However, we need some kind of
  262. synchronization between processes that read and write shared memory.
  263. Consider what happens when a server process wants to send an HTML file to a client process
  264. that resides in the same machine using network mechanisms:
  265. * The server must read the file to memory and pass it to the network functions, that
  266. copy that memory to the OS's internal memory.
  267. * The client uses the network functions to copy the data from the OS's internal memory
  268. to its own memory.
  269. As we can see, there are two copies, one from memory to the network and another one
  270. from the network to memory. And those copies are made using operating system calls
  271. that normally are expensive. Shared memory avoids this overhead, but we need to
  272. synchronize both processes:
  273. * The server maps a shared memory in its address space and also gets access to a
  274. synchronization mechanism. The server obtains exclusive access to the memory using
  275. the synchronization mechanism and copies the file to memory.
  276. * The client maps the shared memory in its address space. Waits until the server releases
  277. the exclusive access and uses the data.
  278. Using shared memory, we can avoid two data copies, but we have to synchronize the access
  279. to the shared memory segment.
  280. [endsect]
  281. [section:shared_memory_steps Creating memory segments that can be shared between processes]
  282. To use shared memory, we have to perform 2 basic steps:
  283. * Request to the operating system a memory segment that can be shared between
  284. processes. The user can create/destroy/open this memory using a [*shared memory object]:
  285. ['An object that represents memory that can be mapped concurrently into the
  286. address space of more than one process.].
  287. * Associate a part of that memory or the whole memory with the address space of the
  288. calling process. The operating system looks for a big enough memory address range
  289. in the calling process' address space and marks that address range as an
  290. special range. Changes in that address range are automatically seen
  291. by other process that also have mapped the same shared memory object.
  292. Once the two steps have been successfully completed, the process can start writing to
  293. and reading from the address space to send to and receive data from other processes.
  294. Now, let's see how can we do this using [*Boost.Interprocess]:
  295. [endsect]
  296. [section:shared_memory_header Header]
  297. To manage shared memory, you just need to include the following header:
  298. [c++]
  299. #include <boost/interprocess/shared_memory_object.hpp>
  300. [endsect]
  301. [section:shared_memory_creating_shared_memory_segments Creating shared memory segments]
  302. As we've mentioned we have to use the `shared_memory_object` class to create, open
  303. and destroy shared memory segments that can be mapped by several processes. We can
  304. specify the access mode of that shared memory object (read only or read-write),
  305. just as if it was a file:
  306. * Create a shared memory segment. Throws if already created:
  307. [c++]
  308. using boost::interprocess;
  309. shared_memory_object shm_obj
  310. (create_only //only create
  311. ,"shared_memory" //name
  312. ,read_write //read-write mode
  313. );
  314. * To open or create a shared memory segment:
  315. [c++]
  316. using boost::interprocess;
  317. shared_memory_object shm_obj
  318. (open_or_create //open or create
  319. ,"shared_memory" //name
  320. ,read_only //read-only mode
  321. );
  322. * To only open a shared memory segment. Throws if does not exist:
  323. [c++]
  324. using boost::interprocess;
  325. shared_memory_object shm_obj
  326. (open_only //only open
  327. ,"shared_memory" //name
  328. ,read_write //read-write mode
  329. );
  330. When a shared memory object is created, its size is 0.
  331. To set the size of the shared memory, the user must use the `truncate` function
  332. call, in a shared memory that has been opened with read-write attributes:
  333. [c++]
  334. shm_obj.truncate(10000);
  335. As shared memory has kernel or filesystem persistence, the user must explicitly
  336. destroy it. The `remove` operation might fail returning
  337. false if the shared memory does not exist, the file is open or the file is
  338. still memory mapped by other processes:
  339. [c++]
  340. using boost::interprocess;
  341. shared_memory_object::remove("shared_memory");
  342. For more details regarding `shared_memory_object` see the
  343. [classref boost::interprocess::shared_memory_object] class reference.
  344. [endsect]
  345. [section:shared_memory_mapping_shared_memory_segments Mapping Shared Memory Segments]
  346. Once created or opened, a process just has to map the shared memory object in the process'
  347. address space. The user can map the whole shared memory or just part of it. The
  348. mapping process is done using the `mapped_region` class. The class represents
  349. a memory region that has been mapped from a shared memory or from other devices
  350. that have also mapping capabilities (for example, files). A `mapped_region` can be
  351. created from any `memory_mappable` object and as you might imagine, `shared_memory_object`
  352. is a `memory_mappable` object:
  353. [c++]
  354. using boost::interprocess;
  355. std::size_t ShmSize = ...
  356. //Map the second half of the memory
  357. mapped_region region
  358. ( shm //Memory-mappable object
  359. , read_write //Access mode
  360. , ShmSize/2 //Offset from the beginning of shm
  361. , ShmSize-ShmSize/2 //Length of the region
  362. );
  363. //Get the address of the region
  364. region.get_address();
  365. //Get the size of the region
  366. region.get_size();
  367. The user can specify the offset from the mappable object where the mapped region
  368. should start and the size of the mapped region. If no offset or size is specified,
  369. the whole mappable object (in this case, shared memory) is mapped. If the offset
  370. is specified, but not the size, the mapped region covers from the offset until
  371. the end of the mappable object.
  372. For more details regarding `mapped_region` see the
  373. [classref boost::interprocess::mapped_region] class reference.
  374. [endsect]
  375. [section:shared_memory_a_simple_example A Simple Example]
  376. Let's see a simple example of shared memory use. A server process creates a
  377. shared memory object, maps it and initializes all the bytes to a value. After that,
  378. a client process opens the shared memory, maps it, and checks
  379. that the data is correctly initialized:
  380. [import ../example/doc_shared_memory.cpp]
  381. [doc_shared_memory]
  382. [endsect]
  383. [section:emulation Emulation for systems without shared memory objects]
  384. [*Boost.Interprocess] provides portable shared memory in terms of POSIX
  385. semantics. Some operating systems don't support shared memory as defined by
  386. POSIX:
  387. * Windows operating systems provide shared memory using memory backed by the
  388. paging file but the lifetime semantics are different from the ones
  389. defined by POSIX (see [link interprocess.sharedmemorybetweenprocesses.sharedmemory.windows_shared_memory
  390. Native windows shared memory] section for more information).
  391. * Some UNIX systems don't fully support POSIX shared memory objects at all.
  392. In those platforms, shared memory is emulated with mapped files created
  393. in a "boost_interprocess" folder created in a temporary files directory.
  394. In Windows platforms, if "Common AppData" key is present
  395. in the registry, "boost_interprocess" folder is created in that directory
  396. (in XP usually "C:\Documents and Settings\All Users\Application Data" and
  397. in Vista "C:\ProgramData").
  398. For Windows platforms without that registry key and Unix systems, shared memory is
  399. created in the system temporary files directory ("/tmp" or similar).
  400. Because of this emulation, shared memory has filesystem lifetime in some
  401. of those systems.
  402. [endsect]
  403. [section:removing Removing shared memory]
  404. [classref boost::interprocess::shared_memory_object shared_memory_object]
  405. provides a static `remove` function to remove a shared memory objects.
  406. This function [*can] fail if the shared memory objects does not exist or
  407. it's opened by another process. Note that this function is similar to the
  408. standard C `int remove(const char *path)` function. In UNIX systems,
  409. `shared_memory_object::remove` calls `shm_unlink`:
  410. * The function will remove the name of the shared memory object
  411. named by the string pointed to by name.
  412. * If one or more references to the shared memory object exist when
  413. is unlinked, the name will be removed before the function returns, but the
  414. removal of the memory object contents will be postponed until all open and
  415. map references to the shared memory object have been removed.
  416. * Even if the object continues to exist after the last function call, reuse of
  417. the name will subsequently cause the creation of a
  418. [classref boost::interprocess::shared_memory_object] instance to behave as if no
  419. shared memory object of this name exists (that is, trying to open an object
  420. with that name will fail and an object of the same name can be created again).
  421. In Windows operating systems, current version supports an usually acceptable emulation
  422. of the UNIX unlink behaviour: the file is renamed with a random name and marked as ['to
  423. be deleted when the last open handle is closed].
  424. [endsect]
  425. [section:anonymous_shared_memory Anonymous shared memory for UNIX systems]
  426. Creating a shared memory segment and mapping it can be a bit tedious when several
  427. processes are involved. When processes are related via `fork()` operating system
  428. call in UNIX systems a simpler method is available using anonymous shared memory.
  429. This feature has been implemented in UNIX systems mapping the device `\dev\zero` or
  430. just using the `MAP_ANONYMOUS` in a POSIX conformant `mmap` system call.
  431. This feature is wrapped in [*Boost.Interprocess] using the `anonymous_shared_memory()`
  432. function, which returns a `mapped_region` object holding an anonymous shared memory
  433. segment that can be shared by related processes.
  434. Here is an example:
  435. [import ../example/doc_anonymous_shared_memory.cpp]
  436. [doc_anonymous_shared_memory]
  437. Once the segment is created, a `fork()` call can
  438. be used so that `region` is used to communicate two related processes.
  439. [endsect]
  440. [section:windows_shared_memory Native windows shared memory]
  441. Windows operating system also offers shared memory, but the lifetime of this
  442. shared memory is very different to kernel or filesystem lifetime. The shared memory
  443. is created backed by the pagefile and it's automatically destroyed when the last
  444. process attached to the shared memory is destroyed.
  445. Because of this reason, there is no effective way to simulate kernel or filesystem
  446. persistence using native windows shared memory and [*Boost.Interprocess] emulates
  447. shared memory using memory mapped files. This assures portability between POSIX
  448. and Windows operating systems.
  449. However, accessing native windows shared memory is a common request of
  450. [*Boost.Interprocess] users because they want to access
  451. to shared memory created with other process that don't use
  452. [*Boost.Interprocess]. In order to manage the native windows shared memory
  453. [*Boost.Interprocess] offers the
  454. [classref boost::interprocess::windows_shared_memory windows_shared_memory] class.
  455. Windows shared memory creation is a bit different from portable shared memory
  456. creation: the size of the segment must be specified when creating the object and
  457. can't be specified through `truncate` like with the shared memory object.
  458. Take in care that when the last process attached to a shared memory is destroyed
  459. [*the shared memory is destroyed] so there is [*no persistency] with native windows
  460. shared memory.
  461. Sharing memory between services and user applications is also different. To share memory
  462. between services and user applications the name of the shared memory must start with the
  463. global namespace prefix `"Global\\"`. This global namespace enables processes on multiple
  464. client sessions to communicate with a service application. The server component can create
  465. the shared memory in the global namespace. Then a client session can use the "Global\" prefix
  466. to open that memory.
  467. The creation of a shared memory object in the global namespace from a session other than
  468. session zero is a privileged operation.
  469. Let's repeat the same example presented for the portable shared memory object:
  470. A server process creates a
  471. shared memory object, maps it and initializes all the bytes to a value. After that,
  472. a client process opens the shared memory, maps it, and checks
  473. that the data is correctly initialized. Take in care that [*if the server exits before
  474. the client connects to the shared memory the client connection will fail], because
  475. the shared memory segment is destroyed when no proces is attached to the memory.
  476. This is the server process:
  477. [import ../example/doc_windows_shared_memory.cpp]
  478. [doc_windows_shared_memory]
  479. As we can see, native windows shared memory needs synchronization to make sure
  480. that the shared memory won't be destroyed before the client is launched.
  481. [endsect]
  482. [section:xsi_shared_memory XSI shared memory]
  483. In many UNIX systems, the OS offers another shared memory memory mechanism, XSI
  484. (X/Open System Interfaces) shared memory segments, also known as "System V" shared memory.
  485. This shared memory mechanism is quite popular and portable, and it's not based in file-mapping
  486. semantics, but it uses special functions (`shmget`, `shmat`, `shmdt`, `shmctl`...).
  487. Unlike POSIX shared memory segments, XSI shared memory segments are not identified by names but
  488. by 'keys' usually created with `ftok`. XSI shared memory segments have kernel lifetime and
  489. must be explicitly removed. XSI shared memory does not support copy-on-write and partial shared memory mapping
  490. but it supports anonymous shared memory.
  491. [*Boost.Interprocess] offers simple ([classref boost::interprocess::xsi_shared_memory xsi_shared_memory])
  492. and managed ([classref boost::interprocess::managed_xsi_shared_memory managed_xsi_shared_memory])
  493. shared memory classes to ease the use of XSI shared memory. It also wraps key creation with the
  494. simple [classref boost::interprocess::xsi_key xsi_key] class.
  495. Let's repeat the same example presented for the portable shared memory object:
  496. A server process creates a shared memory object, maps it and initializes all the bytes to a value. After that,
  497. a client process opens the shared memory, maps it, and checks
  498. that the data is correctly initialized.
  499. This is the server process:
  500. [import ../example/doc_xsi_shared_memory.cpp]
  501. [doc_xsi_shared_memory]
  502. [endsect]
  503. [endsect]
  504. [section:mapped_file Memory Mapped Files]
  505. [section:mapped_file_what_is What is a memory mapped file?]
  506. File mapping is the association of a file's contents with a portion of the address space
  507. of a process. The system creates a file mapping to associate the file and the address
  508. space of the process. A mapped region is the portion of address space that the process
  509. uses to access the file's contents. A single file mapping can have several mapped regions,
  510. so that the user can associate parts of the file with the address space of the process
  511. without mapping the entire file in the address space, since the file can be bigger
  512. than the whole address space of the process (a 9GB DVD image file in a usual 32
  513. bit systems). Processes read from and write to
  514. the file using pointers, just like with dynamic memory. File mapping has the following
  515. advantages:
  516. * Uniform resource use. Files and memory can be treated using the same functions.
  517. * Automatic file data synchronization and cache from the OS.
  518. * Reuse of C++ utilities (STL containers, algorithms) in files.
  519. * Shared memory between two or more applications.
  520. * Allows efficient work with a large files, without mapping the whole file into memory
  521. * If several processes use the same file mapping to create mapped regions of a file, each
  522. process' views contain identical copies of the file on disk.
  523. File mapping is not only used for interprocess communication, it can be used also to
  524. simplify file usage, so the user does not need to use file-management functions to
  525. write the file. The user just writes data to the process memory, and the operating
  526. systems dumps the data to the file.
  527. When two processes map the same file in memory, the memory that one process writes is
  528. seen by another process, so memory mapped files can be used as an interprocess
  529. communication mechanism. We can say that memory-mapped files offer the same interprocess
  530. communication services as shared memory with the addition of filesystem persistence.
  531. However, as the operating system has to synchronize the file contents with the memory
  532. contents, memory-mapped files are not as fast as shared memory.
  533. [endsect]
  534. [section:mapped_file_steps Using mapped files]
  535. To use memory-mapped files, we have to perform 2 basic steps:
  536. * Create a mappable object that represent an already created file of the
  537. filesystem. This object will be used to create multiple mapped regions of the
  538. the file.
  539. * Associate the whole file or parts of the file with the address space of the
  540. calling process. The operating system looks for a big enough memory address range
  541. in the calling process' address space and marks that address range as an
  542. special range. Changes in that address range are automatically seen
  543. by other process that also have mapped the same file and those changes
  544. are also transferred to the disk automatically.
  545. Once the two steps have been successfully completed, the process can start writing to
  546. and reading from the address space to send to and receive data from other processes
  547. and synchronize the file's contents with the changes made to the mapped region.
  548. Now, let's see how can we do this using [*Boost.Interprocess]:
  549. [endsect]
  550. [section:mapped_file_header Header]
  551. To manage mapped files, you just need to include the following header:
  552. [c++]
  553. #include <boost/interprocess/file_mapping.hpp>
  554. [endsect]
  555. [section:mapped_file_creating_file Creating a file mapping]
  556. First, we have to link a file's contents with the process' address space. To do
  557. this, we have to create a mappable object that represents that file. This is
  558. achieved in [*Boost.Interprocess] creating a `file_mapping` object:
  559. [c++]
  560. using boost::interprocess;
  561. file_mapping m_file
  562. ("/usr/home/file" //filename
  563. ,read_write //read-write mode
  564. );
  565. Now we can use the newly created object to create mapped regions. For more details
  566. regarding this class see the
  567. [classref boost::interprocess::file_mapping] class reference.
  568. [endsect]
  569. [section:mapped_file_mapping_regions Mapping File's Contents In Memory]
  570. After creating a file mapping, a process just has to map the shared memory in the
  571. process' address space. The user can map the whole shared memory or just part of it.
  572. The mapping process is done using the `mapped_region` class. as we have said before
  573. The class represents a memory region that has been mapped from a shared memory or from other
  574. devices that have also mapping capabilities:
  575. [c++]
  576. using boost::interprocess;
  577. std::size_t FileSize = ...
  578. //Map the second half of the file
  579. mapped_region region
  580. ( m_file //Memory-mappable object
  581. , read_write //Access mode
  582. , FileSize/2 //Offset from the beginning of shm
  583. , FileSize-FileSize/2 //Length of the region
  584. );
  585. //Get the address of the region
  586. region.get_address();
  587. //Get the size of the region
  588. region.get_size();
  589. The user can specify the offset from the file where the mapped region
  590. should start and the size of the mapped region. If no offset or size is specified,
  591. the whole file is mapped. If the offset is specified, but not the size,
  592. the mapped region covers from the offset until the end of the file.
  593. If several processes map the same file, and a process modifies a memory range
  594. from a mapped region that is also mapped by other process, the changes are
  595. inmedially visible to other processes. However, the file contents on disk are
  596. not updated immediately, since that would hurt performance (writing to disk
  597. is several times slower than writing to memory). If the user wants to make sure
  598. that file's contents have been updated, it can flush a range from the view to disk.
  599. When the function returns, the flushing process has started but there is no guarantee that
  600. all data has been written to disk:
  601. [c++]
  602. //Flush the whole region
  603. region.flush();
  604. //Flush from an offset until the end of the region
  605. region.flush(offset);
  606. //Flush a memory range starting on an offset
  607. region.flush(offset, size);
  608. Remember that the offset is [*not] an offset on the file, but an offset in the
  609. mapped region. If a region covers the second half of a file and flushes the
  610. whole region, only the half of the file is guaranteed to have been flushed.
  611. For more details regarding `mapped_region` see the
  612. [classref boost::interprocess::mapped_region] class reference.
  613. [endsect]
  614. [section:mapped_file_a_simple_example A Simple Example]
  615. Let's reproduce the same example described in the shared memory section, using
  616. memory mapped files. A server process creates a shared
  617. memory segment, maps it and initializes all the bytes to a value. After that,
  618. a client process opens the shared memory, maps it, and checks
  619. that the data is correctly initialized::
  620. [import ../example/doc_file_mapping.cpp]
  621. [doc_file_mapping]
  622. [endsect]
  623. [endsect]
  624. [section:mapped_region More About Mapped Regions]
  625. [section:mapped_region_one_class One Class To Rule Them All]
  626. As we have seen, both `shared_memory_object` and `file_mapping` objects can be used
  627. to create `mapped_region` objects. A mapped region created from a shared memory
  628. object or a file mapping are the same class and this has many advantages.
  629. One can, for example, mix in STL containers mapped regions from shared memory
  630. and memory mapped files. Libraries that only depend on mapped regions can
  631. be used to work with shared memory or memory mapped files without recompiling them.
  632. [endsect]
  633. [section:mapped_region_address_mapping Mapping Address In Several Processes]
  634. In the example we have seen, the file or shared memory contents are mapped
  635. to the address space of the process, but the address was chosen by the operating
  636. system.
  637. If several processes map the same file/shared memory, the mapping address will be
  638. surely different in each process. Since each process might have used its address space
  639. in a different way (allocation of more or less dynamic memory, for example), there is
  640. no guarantee that the file/shared memory is going to be mapped in the same address.
  641. If two processes map the same object in different addresses, this invalidates the use
  642. of pointers in that memory, since the pointer (which is an absolute address) would
  643. only make sense for the process that wrote it. The solution for this is to use offsets
  644. (distance) between objects instead of pointers: If two objects are placed in the same
  645. shared memory segment by one process, [*the address of each object will be different]
  646. in another process but [*the distance between them (in bytes) will be the same].
  647. So the first advice when mapping shared memory and memory mapped files is to avoid
  648. using raw pointers, unless you know what you are doing. Use offsets between data or
  649. relative pointers to obtain pointer functionality when an object placed in a mapped
  650. region wants to point to an object placed in the same mapped region. [*Boost.Interprocess]
  651. offers a smart pointer called [classref boost::interprocess::offset_ptr] that
  652. can be safely placed in shared memory and that can be used to point to another
  653. object placed in the same shared memory / memory mapped file.
  654. [endsect]
  655. [section:mapped_region_fixed_address_mapping Fixed Address Mapping]
  656. The use of relative pointers is less efficient than using raw pointers, so if a user
  657. can succeed mapping the same file or shared memory object in the same address in two
  658. processes, using raw pointers can be a good idea.
  659. To map an object in a fixed address, the user can specify that address in the
  660. `mapped region`'s constructor:
  661. [c++]
  662. mapped_region region ( shm //Map shared memory
  663. , read_write //Map it as read-write
  664. , 0 //Map from offset 0
  665. , 0 //Map until the end
  666. , (void*)0x3F000000 //Map it exactly there
  667. );
  668. However, the user can't map the region in any address, even if the address is not
  669. being used. The offset parameter that marks the start of the mapping region
  670. is also limited. These limitations are explained in the next section.
  671. [endsect]
  672. [section:mapped_region_mapping_problems Mapping Offset And Address Limitations]
  673. As mentioned, the user can't map the memory mappable object at any address and it can
  674. specify the offset of the mappable object that is equivalent to the start of the mapping
  675. region to an arbitrary value.
  676. Most operating systems limit the mapping address and the offset of the mappable object
  677. to a multiple of a value called [*page size]. This is due to the fact that the
  678. [*operating system performs mapping operations over whole pages].
  679. If fixed mapping address is used, ['offset] and ['address]
  680. parameters should be multiples of that value.
  681. This value is, typically, 4KB or 8KB for 32 bit operating systems.
  682. [c++]
  683. //These might fail because the offset is not a multiple of the page size
  684. //and we are using fixed address mapping
  685. mapped_region region1( shm //Map shared memory
  686. , read_write //Map it as read-write
  687. , 1 //Map from offset 1
  688. , 1 //Map 1 byte
  689. , (void*)0x3F000000 //Aligned mapping address
  690. );
  691. //These might fail because the address is not a multiple of the page size
  692. mapped_region region2( shm //Map shared memory
  693. , read_write //Map it as read-write
  694. , 0 //Map from offset 0
  695. , 1 //Map 1 byte
  696. , (void*)0x3F000001 //Not aligned mapping address
  697. );
  698. Since the operating system performs mapping operations over whole pages, specifying
  699. a mapping ['size] or ['offset] that are not multiple of the page size will waste
  700. more resources than necessary. If the user specifies the following 1 byte mapping:
  701. [c++]
  702. //Map one byte of the shared memory object.
  703. //A whole memory page will be used for this.
  704. mapped_region region ( shm //Map shared memory
  705. , read_write //Map it as read-write
  706. , 0 //Map from offset 0
  707. , 1 //Map 1 byte
  708. );
  709. The operating system will reserve a whole page that will not be reused by any
  710. other mapping so we are going to waste [*(page size - 1)] bytes. If we want
  711. to use efficiently operating system resources, we should create regions whose size
  712. is a multiple of [*page size] bytes. If the user specifies the following two
  713. mapped regions for a file with which has `2*page_size` bytes:
  714. //Map the first quarter of the file
  715. //This will use a whole page
  716. mapped_region region1( shm //Map shared memory
  717. , read_write //Map it as read-write
  718. , 0 //Map from offset 0
  719. , page_size/2 //Map page_size/2 bytes
  720. );
  721. //Map the rest of the file
  722. //This will use a 2 pages
  723. mapped_region region2( shm //Map shared memory
  724. , read_write //Map it as read-write
  725. , page_size/2 //Map from offset 0
  726. , 3*page_size/2 //Map the rest of the shared memory
  727. );
  728. In this example, a half of the page is wasted in the first mapping and another
  729. half is wasted in the second because the offset is not a multiple of the
  730. page size. The mapping with the minimum resource usage would be to map whole pages:
  731. //Map the whole first half: uses 1 page
  732. mapped_region region1( shm //Map shared memory
  733. , read_write //Map it as read-write
  734. , 0 //Map from offset 0
  735. , page_size //Map a full page_size
  736. );
  737. //Map the second half: uses 1 page
  738. mapped_region region2( shm //Map shared memory
  739. , read_write //Map it as read-write
  740. , page_size //Map from offset 0
  741. , page_size //Map the rest
  742. );
  743. How can we obtain the [*page size]? The `mapped_region` class has a static
  744. function that returns that value:
  745. [c++]
  746. //Obtain the page size of the system
  747. std::size_t page_size = mapped_region::get_page_size();
  748. The operating system might also limit the number of mapped memory regions per
  749. process or per system.
  750. [endsect]
  751. [endsect]
  752. [section:mapped_region_object_limitations Limitations When Constructing Objects In Mapped Regions]
  753. When two processes create a mapped region of the same mappable object, two processes
  754. can communicate writing and reading that memory. A process could construct a C++ object
  755. in that memory so that the second process can use it. However, a mapped region shared
  756. by multiple processes, can't hold any C++ object, because not every class is ready
  757. to be a process-shared object, specially, if the mapped region is mapped in different
  758. address in each process.
  759. [section:offset_pointer Offset pointers instead of raw pointers]
  760. When placing objects in a mapped region and mapping
  761. that region in different address in every process,
  762. raw pointers are a problem since they are only valid for the
  763. process that placed them there. To solve this, [*Boost.Interprocess] offers
  764. a special smart pointer that can be used instead of a raw pointer.
  765. So user classes containing raw pointers (or Boost smart pointers, that
  766. internally own a raw pointer) can't be safely placed in a process shared
  767. mapped region. These pointers must be replaced with offset pointers, and
  768. these pointers must point only to objects placed in the same mapped region
  769. if you want to use these shared objects from different processes.
  770. Of course, a pointer placed in a mapped region shared between processes should
  771. only point to an object of that mapped region. Otherwise, the pointer would
  772. point to an address that it's only valid one process and other
  773. processes may crash when accessing to that address.
  774. [endsect]
  775. [section:references_forbidden References forbidden]
  776. References suffer from the same problem as pointers
  777. (mainly because they are implemented as pointers).
  778. However, it is not possible to create a fully workable
  779. smart reference currently in C++ (for example,
  780. `operator .()` can't be overloaded). Because of this,
  781. if the user wants to put an object in shared memory,
  782. the object can't have any (smart or not) reference
  783. as a member.
  784. References will only work if the mapped region is mapped in the same
  785. base address in all processes sharing a memory segment.
  786. Like pointers, a reference placed in a mapped region should only point
  787. to an object of that mapped region.
  788. [endsect]
  789. [section:virtuality_limitation Virtuality forbidden]
  790. The virtual table pointer and the virtual table
  791. are in the address space of the process
  792. that constructs the object, so if we place a class
  793. with a virtual function or virtual base class, the virtual
  794. pointer placed in shared memory will be invalid for other processes
  795. and they will crash.
  796. This problem is very difficult to solve, since each process needs a
  797. different virtual table pointer and the object that contains that pointer
  798. is shared across many processes. Even if we map the mapped region in
  799. the same address in every process, the virtual table can be in a different
  800. address in every process. To enable virtual functions for objects
  801. shared between processes, deep compiler changes are needed and virtual
  802. functions would suffer a performance hit. That's why
  803. [*Boost.Interprocess] does not have any plan to support virtual function
  804. and virtual inheritance in mapped regions shared between processes.
  805. [endsect]
  806. [section:statics_warning Be careful with static class members]
  807. Static members of classes are global objects shared by
  808. all instances of the class. Because of this, static
  809. members are implemented as global variables in processes.
  810. When constructing a class with static members, each process
  811. has its own copy of the static member, so updating a static
  812. member in one process does not change the value of the static
  813. member the another process. So be careful with these classes. Static
  814. members are not dangerous if they are just constant variables initialized
  815. when the process starts, but they don't change at all (for example,
  816. when used like enums) and their value is the same for all processes.
  817. [endsect]
  818. [endsect]
  819. [endsect]
  820. [section:offset_ptr Mapping Address Independent Pointer: offset_ptr]
  821. When creating shared memory and memory mapped files to communicate two
  822. processes the memory segment can be mapped in a different address in each process:
  823. [c++]
  824. #include<boost/interprocess/shared_memory_object.hpp>
  825. // ...
  826. using boost::interprocess;
  827. //Open a shared memory segment
  828. shared_memory_object shm_obj
  829. (open_only //open or create
  830. ,"shared_memory" //name
  831. ,read_only //read-only mode
  832. );
  833. //Map the whole shared memory
  834. mapped_region region
  835. ( shm //Memory-mappable object
  836. , read_write //Access mode
  837. );
  838. //This address can be different in each process
  839. void *addr = region.get_address();
  840. This makes the creation of complex objects in mapped regions difficult: a C++
  841. class instance placed in a mapped region might have a pointer pointing to
  842. another object also placed in the mapped region. Since the pointer stores an
  843. absolute address, that address is only valid for the process that placed
  844. the object there unless all processes map the mapped region in the same
  845. address.
  846. To be able to simulate pointers in mapped regions, users must use [*offsets]
  847. (distance between objects) instead of absolute addresses. The offset between
  848. two objects in a mapped region is the same for any process that maps the
  849. mapped region, even if that region is placed in different base addresses.
  850. To facilitate the use of offsets, [*Boost.Interprocess] offers
  851. [classref boost::interprocess::offset_ptr offset_ptr].
  852. [classref boost::interprocess::offset_ptr offset_ptr]
  853. wraps all the background operations
  854. needed to offer a pointer-like interface. The class interface is
  855. inspired in Boost Smart Pointers and this smart pointer
  856. stores the offset (distance in bytes)
  857. between the pointee's address and it's own `this` pointer.
  858. Imagine a structure in a common
  859. 32 bit processor:
  860. [c++]
  861. struct structure
  862. {
  863. int integer1; //The compiler places this at offset 0 in the structure
  864. offset_ptr<int> ptr; //The compiler places this at offset 4 in the structure
  865. int integer2; //The compiler places this at offset 8 in the structure
  866. };
  867. //...
  868. structure s;
  869. //Assign the address of "integer1" to "ptr".
  870. //"ptr" will store internally "-4":
  871. // (char*)&s.integer1 - (char*)&s.ptr;
  872. s.ptr = &s.integer1;
  873. //Assign the address of "integer2" to "ptr".
  874. //"ptr" will store internally "4":
  875. // (char*)&s.integer2 - (char*)&s.ptr;
  876. s.ptr = &s.integer2;
  877. One of the big problems of
  878. `offset_ptr` is the representation of the null pointer. The null pointer
  879. can't be safely represented like an offset, since the absolute address 0
  880. is always outside of the mapped region. Due to the fact that the segment can be mapped
  881. in a different base address in each process the distance between the address 0
  882. and `offset_ptr` is different for every process.
  883. Some implementations choose the offset 0 (that is, an `offset_ptr`
  884. pointing to itself) as the null pointer pointer representation
  885. but this is not valid for many use cases
  886. since many times structures like linked lists or nodes from STL containers
  887. point to themselves (the
  888. end node in an empty container, for example) and 0 offset value
  889. is needed. An alternative is to store, in addition to the offset, a boolean
  890. to indicate if the pointer is null. However, this increments the size of the
  891. pointer and hurts performance.
  892. In consequence,
  893. [classref boost::interprocess::offset_ptr offset_ptr] defines offset 1
  894. as the null pointer, meaning that this class [*can't] point to the byte
  895. after its own ['this] pointer:
  896. [c++]
  897. using namespace boost::interprocess;
  898. offset_ptr<char> ptr;
  899. //Pointing to the next byte of it's own address
  900. //marks the smart pointer as null.
  901. ptr = (char*)&ptr + 1;
  902. //ptr is equal to null
  903. assert(!ptr);
  904. //This is the same as assigning the null value...
  905. ptr = 0;
  906. //ptr is also equal to null
  907. assert(!ptr);
  908. In practice, this limitation is not important, since a user almost never
  909. wants to point to this address.
  910. [classref boost::interprocess::offset_ptr offset_ptr]
  911. offers all pointer-like operations and
  912. random_access_iterator typedefs, so it can be used in STL
  913. algorithms requiring random access iterators and detected via traits.
  914. For more information about the members and operations of the class, see
  915. [classref boost::interprocess::offset_ptr offset_ptr reference].
  916. [endsect]
  917. [section:synchronization_mechanisms Synchronization mechanisms]
  918. [section:synchronization_mechanisms_overview Synchronization mechanisms overview]
  919. As mentioned before, the ability to shared memory between processes through memory
  920. mapped files or shared memory objects is not very useful if the access to that
  921. memory can't be effectively synchronized. This is the same problem that happens with
  922. thread-synchronization mechanisms, where heap memory and global variables are
  923. shared between threads, but the access to these resources needs to be synchronized
  924. typically through mutex and condition variables. [*Boost.Threads] implements these
  925. synchronization utilities between threads inside the same process. [*Boost.Interprocess]
  926. implements similar mechanisms to synchronize threads from different processes.
  927. [section:synchronization_mechanisms_named_vs_anonymous Named And Anonymous Synchronization Mechanisms]
  928. [*Boost.Interprocess] presents two types of synchronization objects:
  929. * [*Named utilities]: When two processes want
  930. to create an object of such type, both processes must ['create] or ['open] an object
  931. using the same name. This is similar to creating or opening files: a process creates
  932. a file with using a `fstream` with the name ['filename] and another process opens
  933. that file using another `fstream` with the same ['filename] argument.
  934. [*Each process uses a different object to access to the resource, but both processes
  935. are using the same underlying resource].
  936. * [*Anonymous utilities]: Since these utilities have no name, two processes must
  937. share [*the same object] through shared memory or memory mapped files. This is
  938. similar to traditional thread synchronization objects: [*Both processes share the
  939. same object]. Unlike thread synchronization, where global variables and heap
  940. memory is shared between threads of the same process, sharing objects between
  941. two threads from different process can be only possible through mapped regions
  942. that map the same mappable resource (for example, shared memory or memory mapped files).
  943. Each type has it's own advantages and disadvantages:
  944. * Named utilities are easier to handle for simple synchronization tasks, since both process
  945. don't have to create a shared memory region and construct the synchronization mechanism there.
  946. * Anonymous utilities can be serialized to disk when using memory mapped objects obtaining
  947. automatic persistence of synchronization utilities. One could construct a synchronization
  948. utility in a memory mapped file, reboot the system, map the file again, and use the
  949. synchronization utility again without any problem. This can't be achieved with named
  950. synchronization utilities.
  951. The main interface difference between named and anonymous utilities are the constructors.
  952. Usually anonymous utilities have only one constructor, whereas the named utilities have
  953. several constructors whose first argument is a special type that requests creation,
  954. opening or opening or creation of the underlying resource:
  955. [c++]
  956. using namespace boost::interprocess;
  957. //Create the synchronization utility. If it previously
  958. //exists, throws an error
  959. NamedUtility(create_only, ...)
  960. //Open the synchronization utility. If it does not previously
  961. //exist, it's created.
  962. NamedUtility(open_or_create, ...)
  963. //Open the synchronization utility. If it does not previously
  964. //exist, throws an error.
  965. NamedUtility(open_only, ...)
  966. On the other hand the anonymous synchronization utility can only
  967. be created and the processes must synchronize using other mechanisms
  968. who creates the utility:
  969. [c++]
  970. using namespace boost::interprocess;
  971. //Create the synchronization utility.
  972. AnonymousUtility(...)
  973. [endsect]
  974. [section:synchronization_mechanisms_types Types Of Synchronization Mechanisms]
  975. Apart from its named/anonymous nature, [*Boost.Interprocess] presents the following
  976. synchronization utilities:
  977. * Mutexes (named and anonymous)
  978. * Condition variables (named and anonymous)
  979. * Semaphores (named and anonymous)
  980. * Upgradable mutexes
  981. * File locks
  982. [endsect]
  983. [endsect]
  984. [section:mutexes Mutexes]
  985. [section:mutexes_whats_a_mutex What's A Mutex?]
  986. ['Mutex] stands for [*mut]ual [*ex]clusion and it's the most basic form of
  987. synchronization between processes.
  988. Mutexes guarantee that only one thread can lock a given mutex. If a code section
  989. is surrounded by a mutex locking and unlocking, it's guaranteed that only a thread
  990. at a time executes that section of code.
  991. When that thread [*unlocks] the mutex, other threads can enter to that code
  992. region:
  993. [c++]
  994. //The mutex has been previously constructed
  995. lock_the_mutex();
  996. //This code will be executed only by one thread
  997. //at a time.
  998. unlock_the_mutex();
  999. A mutex can also be [*recursive] or [*non-recursive]:
  1000. * Recursive mutexes can be locked several times by the same thread. To fully unlock the
  1001. mutex, the thread has to unlock the mutex the same times it has locked it.
  1002. * Non-recursive mutexes can't be locked several times by the same thread. If a mutex
  1003. is locked twice by a thread, the result is undefined, it might throw an error or
  1004. the thread could be blocked forever.
  1005. [endsect]
  1006. [section:mutexes_mutex_operations Mutex Operations]
  1007. All the mutex types from [*Boost.Interprocess] implement the following operations:
  1008. [blurb ['[*void lock()]]]
  1009. [*Effects:]
  1010. The calling thread tries to obtain ownership of the mutex, and if another thread has ownership of the mutex, it waits until it can obtain the ownership. If a thread takes ownership of the mutex the mutex must be unlocked by the same thread. If the mutex supports recursive locking, the mutex must be unlocked the same number of times it is locked.
  1011. [*Throws:] *interprocess_exception* on error.
  1012. [blurb ['[*bool try_lock()]]]
  1013. [*Effects:] The calling thread tries to obtain ownership of the mutex, and if another thread has ownership of the mutex returns immediately. If the mutex supports recursive locking, the mutex must be unlocked the same number of times it is locked.
  1014. [*Returns:] If the thread acquires ownership of the mutex, returns true, if the another thread has ownership of the mutex, returns false.
  1015. [*Throws:] *interprocess_exception* on error.
  1016. [blurb ['[*bool timed_lock(const boost::posix_time::ptime &abs_time)]]]
  1017. [*Effects:] The calling thread will try to obtain exclusive ownership of the mutex if it can do so in until the specified time is reached. If the mutex supports recursive locking, the mutex must be unlocked the same number of times it is locked.
  1018. [*Returns:] If the thread acquires ownership of the mutex, returns true, if the timeout expires returns false.
  1019. [*Throws:] *interprocess_exception* on error.
  1020. [blurb ['[*void unlock()]]]
  1021. [*Precondition:] The thread must have exclusive ownership of the mutex.
  1022. [*Effects:] The calling thread releases the exclusive ownership of the mutex. If the mutex supports recursive locking, the mutex must be unlocked the same number of times it is locked.
  1023. [*Throws:] An exception derived from *interprocess_exception* on error.
  1024. [important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
  1025. are UTC time points, not local time points]
  1026. [endsect]
  1027. [section:mutexes_interprocess_mutexes Boost.Interprocess Mutex Types And Headers]
  1028. Boost.Interprocess offers the following mutex types:
  1029. [c++]
  1030. #include <boost/interprocess/sync/interprocess_mutex.hpp>
  1031. * [classref boost::interprocess::interprocess_mutex interprocess_mutex]: A non-recursive,
  1032. anonymous mutex that can be placed in shared memory or memory mapped files.
  1033. [c++]
  1034. #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
  1035. * [classref boost::interprocess::interprocess_recursive_mutex interprocess_recursive_mutex]: A recursive,
  1036. anonymous mutex that can be placed in shared memory or memory mapped files.
  1037. [c++]
  1038. #include <boost/interprocess/sync/named_mutex.hpp>
  1039. * [classref boost::interprocess::named_mutex named_mutex]: A non-recursive,
  1040. named mutex.
  1041. [c++]
  1042. #include <boost/interprocess/sync/named_recursive_mutex.hpp>
  1043. * [classref boost::interprocess::named_recursive_mutex named_recursive_mutex]: A recursive,
  1044. named mutex.
  1045. [endsect]
  1046. [section:mutexes_scoped_lock Scoped lock]
  1047. It's very important to unlock a mutex after the process has read or written the data.
  1048. This can be difficult when dealing with exceptions, so usually mutexes are used
  1049. with a scoped lock, a class that can guarantee that a mutex will always be unlocked
  1050. even when an exception occurs. To use a scoped lock just include:
  1051. [c++]
  1052. #include <boost/interprocess/sync/scoped_lock.hpp>
  1053. Basically, a scoped lock calls [*unlock()] in its destructor, and a mutex is always
  1054. unlocked when an exception occurs. Scoped lock has many constructors to lock,
  1055. try_lock, timed_lock a mutex or not to lock it at all.
  1056. [c++]
  1057. using namespace boost::interprocess;
  1058. //Let's create any mutex type:
  1059. MutexType mutex;
  1060. {
  1061. //This will lock the mutex
  1062. scoped_lock<MutexType> lock(mutex);
  1063. //Some code
  1064. //The mutex will be unlocked here
  1065. }
  1066. {
  1067. //This will try_lock the mutex
  1068. scoped_lock<MutexType> lock(mutex, try_to_lock);
  1069. //Check if the mutex has been successfully locked
  1070. if(lock){
  1071. //Some code
  1072. }
  1073. //If the mutex was locked it will be unlocked
  1074. }
  1075. {
  1076. boost::posix_time::ptime abs_time = ...
  1077. //This will timed_lock the mutex
  1078. scoped_lock<MutexType> lock(mutex, abs_time);
  1079. //Check if the mutex has been successfully locked
  1080. if(lock){
  1081. //Some code
  1082. }
  1083. //If the mutex was locked it will be unlocked
  1084. }
  1085. For more information, check the
  1086. [classref boost::interprocess::scoped_lock scoped_lock's reference].
  1087. [important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
  1088. are UTC time points, not local time points]
  1089. [endsect]
  1090. [section:mutexes_anonymous_example Anonymous mutex example]
  1091. Imagine that two processes need to write traces to a cyclic buffer built
  1092. in shared memory. Each process needs to obtain exclusive access to the
  1093. cyclic buffer, write the trace and continue.
  1094. To protect the cyclic buffer, we can store a process shared mutex in the
  1095. cyclic buffer. Each process will lock the mutex before writing the data and
  1096. will write a flag when ends writing the traces
  1097. (`doc_anonymous_mutex_shared_data.hpp` header):
  1098. [import ../example/doc_anonymous_mutex_shared_data.hpp]
  1099. [doc_anonymous_mutex_shared_data]
  1100. This is the process main process. Creates the shared memory, constructs
  1101. the cyclic buffer and start writing traces:
  1102. [import ../example/comp_doc_anonymous_mutexA.cpp]
  1103. [doc_anonymous_mutexA]
  1104. The second process opens the shared memory, obtains access to the cyclic buffer
  1105. and starts writing traces:
  1106. [import ../example/comp_doc_anonymous_mutexB.cpp]
  1107. [doc_anonymous_mutexB]
  1108. As we can see, a mutex is useful to protect data but not to notify an event to another
  1109. process. For this, we need a condition variable, as we will see in the next section.
  1110. [endsect]
  1111. [section:mutexes_named_example Named mutex example]
  1112. Now imagine that two processes want to write a trace to a file. First they write
  1113. their name, and after that they write the message. Since the operating system can
  1114. interrupt a process in any moment we can mix parts of the messages of both processes,
  1115. so we need a way to write the whole message to the file atomically. To achieve this,
  1116. we can use a named mutex so that each process locks the mutex before writing:
  1117. [import ../example/doc_named_mutex.cpp]
  1118. [doc_named_mutex]
  1119. [endsect]
  1120. [endsect]
  1121. [section:conditions Conditions]
  1122. [section:conditions_whats_a_condition What's A Condition Variable?]
  1123. In the previous example, a mutex is used to ['lock] but we can't use it to
  1124. ['wait] efficiently until the condition to continue is met. A condition variable
  1125. can do two things:
  1126. * [*wait]: The thread is blocked until some other thread notifies that it can
  1127. continue because the condition that lead to waiting has disappeared.
  1128. * [*notify]: The thread sends a signal to one blocked thread or to all blocked
  1129. threads to tell them that they the condition that provoked their wait has
  1130. disappeared.
  1131. Waiting in a condition variable is always associated with a mutex.
  1132. The mutex must be locked prior to waiting on the condition. When waiting
  1133. on the condition variable, the thread unlocks the mutex and waits [*atomically].
  1134. When the thread returns from a wait function (because of a signal or a timeout,
  1135. for example) the mutex object is again locked.
  1136. [endsect]
  1137. [section:conditions_interprocess_conditions Boost.Interprocess Condition Types And Headers]
  1138. Boost.Interprocess offers the following condition types:
  1139. [c++]
  1140. #include <boost/interprocess/sync/interprocess_condition.hpp>
  1141. * [classref boost::interprocess::interprocess_condition interprocess_condition]:
  1142. An anonymous condition variable that can be placed in shared memory or memory
  1143. mapped files to be used with [classref boost::interprocess::interprocess_mutex].
  1144. [c++]
  1145. #include <boost/interprocess/sync/interprocess_condition_any.hpp>
  1146. * [classref boost::interprocess::interprocess_condition_any interprocess_condition_any]:
  1147. An anonymous condition variable that can be placed in shared memory or memory
  1148. mapped files to be used with any lock type.
  1149. [c++]
  1150. #include <boost/interprocess/sync/named_condition.hpp>
  1151. * [classref boost::interprocess::named_condition named_condition]: A named
  1152. condition variable to be used with [classref boost::interprocess::named_mutex named_mutex].
  1153. [c++]
  1154. #include <boost/interprocess/sync/named_condition_any.hpp>
  1155. * [classref boost::interprocess::named_condition named_condition]: A named
  1156. condition variable to be used with any lock type.
  1157. Named conditions are similar to anonymous conditions, but they are used in
  1158. combination with named mutexes. Several times, we don't want to store
  1159. synchronization objects with the synchronized data:
  1160. * We want to change the synchronization method (from interprocess
  1161. to intra-process, or without any synchronization) using the same data.
  1162. Storing the process-shared anonymous synchronization with the synchronized
  1163. data would forbid this.
  1164. * We want to send the synchronized data through the network or any other
  1165. communication method. Sending the process-shared synchronization objects
  1166. wouldn't have any sense.
  1167. [endsect]
  1168. [section:conditions_anonymous_example Anonymous condition example]
  1169. Imagine that a process that writes a trace to a simple shared memory buffer that
  1170. another process prints one by one. The first process writes the trace and waits
  1171. until the other process prints the data. To achieve this, we can use two
  1172. condition variables: the first one is used to block the sender until the second
  1173. process prints the message and the second one to block the receiver until the
  1174. buffer has a trace to print.
  1175. The shared memory trace buffer (doc_anonymous_condition_shared_data.hpp):
  1176. [import ../example/doc_anonymous_condition_shared_data.hpp]
  1177. [doc_anonymous_condition_shared_data]
  1178. This is the process main process. Creates the shared memory, places there
  1179. the buffer and starts writing messages one by one until it writes "last message"
  1180. to indicate that there are no more messages to print:
  1181. [import ../example/comp_doc_anonymous_conditionA.cpp]
  1182. [doc_anonymous_conditionA]
  1183. The second process opens the shared memory and prints each message
  1184. until the "last message" message is received:
  1185. [import ../example/comp_doc_anonymous_conditionB.cpp]
  1186. [doc_anonymous_conditionB]
  1187. With condition variables, a process can block if it can't continue the work,
  1188. and when the conditions to continue are met another process can wake it.
  1189. [endsect]
  1190. [endsect]
  1191. [section:semaphores Semaphores]
  1192. [section:semaphores_whats_a_semaphores What's A Semaphore?]
  1193. A semaphore is a synchronization mechanism between processes based in an internal
  1194. count that offers two basic operations:
  1195. * [*Wait]: Tests the value of the semaphore count, and waits if the value is less than or
  1196. equal than 0. Otherwise, decrements the semaphore count.
  1197. * [*Post]: Increments the semaphore count. If any process is blocked, one of those processes
  1198. is awoken.
  1199. If the initial semaphore count is initialized to 1, a [*Wait] operation is equivalent to a
  1200. mutex locking and [*Post] is equivalent to a mutex unlocking. This type of semaphore is known
  1201. as a [*binary semaphore].
  1202. Although semaphores can be used like mutexes, they have a unique feature: unlike mutexes,
  1203. a [*Post] operation need not be executed by the same thread/process that executed the
  1204. [*Wait] operation.
  1205. [endsect]
  1206. [section:semaphores_interprocess_semaphores Boost.Interprocess Semaphore Types And Headers]
  1207. Boost.Interprocess offers the following semaphore types:
  1208. [c++]
  1209. #include <boost/interprocess/sync/interprocess_semaphore.hpp>
  1210. * [classref boost::interprocess::interprocess_semaphore interprocess_semaphore]:
  1211. An anonymous semaphore that can be placed in shared memory or memory
  1212. mapped files.
  1213. [c++]
  1214. #include <boost/interprocess/sync/named_semaphore.hpp>
  1215. * [classref boost::interprocess::named_semaphore named_semaphore]: A named
  1216. semaphore.
  1217. [endsect]
  1218. [section:semaphores_anonymous_example Anonymous semaphore example]
  1219. We will implement an integer array in shared memory that will be used to transfer data
  1220. from one process to another process. The first process will write some integers
  1221. to the array and the process will block if the array is full.
  1222. The second process will copy the transmitted data to its own buffer, blocking if
  1223. there is no new data in the buffer.
  1224. This is the shared integer array (doc_anonymous_semaphore_shared_data.hpp):
  1225. [import ../example/doc_anonymous_semaphore_shared_data.hpp]
  1226. [doc_anonymous_semaphore_shared_data]
  1227. This is the process main process. Creates the shared memory, places there
  1228. the integer array and starts integers one by one, blocking if the array
  1229. is full:
  1230. [import ../example/comp_doc_anonymous_semaphoreA.cpp]
  1231. [doc_anonymous_semaphoreA]
  1232. The second process opens the shared memory and copies the received integers
  1233. to it's own buffer:
  1234. [import ../example/comp_doc_anonymous_semaphoreB.cpp]
  1235. [doc_anonymous_semaphoreB]
  1236. The same interprocess communication can be achieved with a condition variables
  1237. and mutexes, but for several synchronization patterns, a semaphore is more
  1238. efficient than a mutex/condition combination.
  1239. [endsect]
  1240. [endsect]
  1241. [section:sharable_upgradable_mutexes Sharable and Upgradable Mutexes]
  1242. [section:upgradable_whats_a_mutex What's a Sharable and an Upgradable Mutex?]
  1243. Sharable and upgradable mutex are special mutex types that offers more locking possibilities
  1244. than a normal mutex. Sometimes, we can distinguish between [*reading] the data and
  1245. [*modifying] the data. If just some threads need to modify the data, and a plain mutex
  1246. is used to protect the data from concurrent access, concurrency is pretty limited:
  1247. two threads that only read the data will be serialized instead of being executed
  1248. concurrently.
  1249. If we allow concurrent access to threads that just read the data but we avoid
  1250. concurrent access between threads that read and modify or between threads that modify,
  1251. we can increase performance. This is specially true in applications where data reading
  1252. is more common than data modification and the synchronized data reading code needs
  1253. some time to execute. With a sharable mutex we can acquire 2 lock types:
  1254. * [*Exclusive lock]: Similar to a plain mutex. If a thread acquires an exclusive
  1255. lock, no other thread can acquire any lock (exclusive or other) until the exclusive
  1256. lock is released. If any thread other has any lock other than exclusive, a thread trying
  1257. to acquire an exclusive lock will block.
  1258. This lock will be acquired by threads that will modify the data.
  1259. * [*Sharable lock]: If a thread acquires a sharable lock, other threads
  1260. can't acquire the exclusive lock. If any thread has acquired
  1261. the exclusive lock a thread trying to acquire a sharable lock will block.
  1262. This locking is executed by threads that just need to read the data.
  1263. With an upgradable mutex we can acquire previous locks plus a new upgradable lock:
  1264. * [*Upgradable lock]: Acquiring an upgradable lock is similar to acquiring
  1265. a [*privileged sharable lock]. If a thread acquires an upgradable lock, other threads
  1266. can acquire a sharable lock. If any thread has acquired the exclusive or upgradable lock
  1267. a thread trying to acquire an upgradable lock will block.
  1268. A thread that has acquired an upgradable lock,
  1269. is guaranteed to be able to acquire atomically an exclusive lock when other threads
  1270. that have acquired a sharable lock release it. This is used for
  1271. a thread that [*maybe] needs to modify the data, but usually just needs to read the data.
  1272. This thread acquires the upgradable lock and other threads can acquire the sharable lock.
  1273. If the upgradable thread reads the data and it has to modify it, the thread can be promoted
  1274. to acquire the exclusive lock: when all sharable threads have released the sharable lock, the
  1275. upgradable lock is atomically promoted to an exclusive lock. The newly promoted thread
  1276. can modify the data and it can be sure that no other thread has modified it while
  1277. doing the transition. [*Only 1 thread can acquire the upgradable
  1278. (privileged reader) lock].
  1279. To sum up:
  1280. [table Locking Possibilities for a Sharable Mutex
  1281. [[If a thread has acquired the...] [Other threads can acquire...]]
  1282. [[Sharable lock] [many sharable locks]]
  1283. [[Exclusive lock] [no locks]]
  1284. ]
  1285. [table Locking Possibilities for an Upgradable Mutex
  1286. [[If a thread has acquired the...] [Other threads can acquire...]]
  1287. [[Sharable lock] [many sharable locks and 1 upgradable lock]]
  1288. [[Upgradable lock] [many sharable locks]]
  1289. [[Exclusive lock] [no locks]]
  1290. ]
  1291. [endsect]
  1292. [section:upgradable_transitions Lock transitions for Upgradable Mutex]
  1293. A sharable mutex has no option to change the acquired lock for another lock
  1294. atomically.
  1295. On the other hand, for an upgradable mutex, a thread that has
  1296. acquired a lock can try to acquire another lock type atomically.
  1297. All lock transitions are not guaranteed to succeed. Even if a transition is guaranteed
  1298. to succeed, some transitions will block the thread waiting until other threads release
  1299. the sharable locks. [*Atomically] means that no other thread will acquire an Upgradable
  1300. or Exclusive lock in the transition, [*so data is guaranteed to remain unchanged]:
  1301. [table Transition Possibilities for an Upgradable Mutex
  1302. [[If a thread has acquired the...] [It can atomically release the previous lock and...]]
  1303. [[Sharable lock] [try to obtain (not guaranteed) immediately the Exclusive lock if no other thread has exclusive or upgrable lock]]
  1304. [[Sharable lock] [try to obtain (not guaranteed) immediately the Upgradable lock if no other thread has exclusive or upgrable lock]]
  1305. [[Upgradable lock] [obtain the Exclusive lock when all sharable locks are released]]
  1306. [[Upgradable lock] [obtain the Sharable lock immediately]]
  1307. [[Exclusive lock] [obtain the Upgradable lock immediately]]
  1308. [[Exclusive lock] [obtain the Sharable lock immediately]]
  1309. ]
  1310. As we can see, an upgradable mutex is a powerful synchronization utility that can improve
  1311. the concurrency. However, if most of the time we have to modify the data, or the
  1312. synchronized code section is very short, it's more efficient to use a plain mutex, since
  1313. it has less overhead. Upgradable lock shines when the synchronized code section is bigger
  1314. and there are more readers than modifiers.
  1315. [endsect]
  1316. [section:sharable_upgradable_mutexes_operations Upgradable Mutex Operations]
  1317. All the upgradable mutex types from [*Boost.Interprocess] implement
  1318. the following operations:
  1319. [section:sharable_upgradable_mutexes_operations_exclusive Exclusive Locking (Sharable & Upgradable Mutexes)]
  1320. [blurb ['[*void lock()]]]
  1321. [*Effects:]
  1322. The calling thread tries to obtain exclusive ownership of the mutex, and if
  1323. another thread has any ownership of the mutex (exclusive or other),
  1324. it waits until it can obtain the ownership.
  1325. [*Throws:] *interprocess_exception* on error.
  1326. [blurb ['[*bool try_lock()]]]
  1327. [*Effects:]
  1328. The calling thread tries to acquire exclusive ownership of the mutex without
  1329. waiting. If no other thread has any ownership of the mutex (exclusive or other)
  1330. this succeeds.
  1331. [*Returns:] If it can acquire exclusive ownership immediately returns true.
  1332. If it has to wait, returns false.
  1333. [*Throws:] *interprocess_exception* on error.
  1334. [blurb ['[*bool timed_lock(const boost::posix_time::ptime &abs_time)]]]
  1335. [*Effects:]
  1336. The calling thread tries to acquire exclusive ownership of the mutex
  1337. waiting if necessary until no other thread has any ownership of the mutex
  1338. (exclusive or other) or abs_time is reached.
  1339. [*Returns:] If acquires exclusive ownership, returns true. Otherwise
  1340. returns false.
  1341. [*Throws:] *interprocess_exception* on error.
  1342. [blurb ['[*void unlock()]]]
  1343. [*Precondition:] The thread must have exclusive ownership of the mutex.
  1344. [*Effects:] The calling thread releases the exclusive ownership of the mutex.
  1345. [*Throws:] An exception derived from *interprocess_exception* on error.
  1346. [endsect]
  1347. [section:sharable_upgradable_mutexes_operations_sharable Sharable Locking (Sharable & Upgradable Mutexes)]
  1348. [blurb ['[*void lock_sharable()]]]
  1349. [*Effects:]
  1350. The calling thread tries to obtain sharable ownership of the mutex, and if
  1351. another thread has exclusive ownership of the mutex,
  1352. waits until it can obtain the ownership.
  1353. [*Throws:] *interprocess_exception* on error.
  1354. [blurb ['[*bool try_lock_sharable()]]]
  1355. [*Effects:]
  1356. The calling thread tries to acquire sharable ownership of the mutex without
  1357. waiting. If no other thread has exclusive ownership of
  1358. the mutex this succeeds.
  1359. [*Returns:] If it can acquire sharable ownership immediately returns true.
  1360. If it has to wait, returns false.
  1361. [*Throws:] *interprocess_exception* on error.
  1362. [blurb ['[*bool timed_lock_sharable(const boost::posix_time::ptime &abs_time)]]]
  1363. [*Effects:]
  1364. The calling thread tries to acquire sharable ownership of the mutex
  1365. waiting if necessary until no other thread has exclusive
  1366. ownership of the mutex or abs_time is reached.
  1367. [*Returns:] If acquires sharable ownership, returns true. Otherwise
  1368. returns false.
  1369. [*Throws:] *interprocess_exception* on error.
  1370. [blurb ['[*void unlock_sharable()]]]
  1371. [*Precondition:] The thread must have sharable ownership of the mutex.
  1372. [*Effects:] The calling thread releases the sharable ownership of the mutex.
  1373. [*Throws:] An exception derived from *interprocess_exception* on error.
  1374. [endsect]
  1375. [section:upgradable_mutexes_operations_upgradable Upgradable Locking (Upgradable Mutex only)]
  1376. [blurb ['[*void lock_upgradable()]]]
  1377. [*Effects:]
  1378. The calling thread tries to obtain upgradable ownership of the mutex, and if
  1379. another thread has exclusive or upgradable ownership of the mutex,
  1380. waits until it can obtain the ownership.
  1381. [*Throws:] *interprocess_exception* on error.
  1382. [blurb ['[*bool try_lock_upgradable()]]]
  1383. [*Effects:]
  1384. The calling thread tries to acquire upgradable ownership of the mutex without
  1385. waiting. If no other thread has exclusive or upgradable ownership of
  1386. the mutex this succeeds.
  1387. [*Returns:] If it can acquire upgradable ownership immediately returns true.
  1388. If it has to wait, returns false.
  1389. [*Throws:] *interprocess_exception* on error.
  1390. [blurb ['[*bool timed_lock_upgradable(const boost::posix_time::ptime &abs_time)]]]
  1391. [*Effects:]
  1392. The calling thread tries to acquire upgradable ownership of the mutex
  1393. waiting if necessary until no other thread has exclusive
  1394. ownership of the mutex or abs_time is reached.
  1395. [*Returns:] If acquires upgradable ownership, returns true. Otherwise
  1396. returns false.
  1397. [*Throws:] *interprocess_exception* on error.
  1398. [blurb ['[*void unlock_upgradable()]]]
  1399. [*Precondition:] The thread must have upgradable ownership of the mutex.
  1400. [*Effects:] The calling thread releases the upgradable ownership of the mutex.
  1401. [*Throws:] An exception derived from *interprocess_exception* on error.
  1402. [endsect]
  1403. [section:upgradable_mutexes_operations_demotions Demotions (Upgradable Mutex only)]
  1404. [blurb ['[*void unlock_and_lock_upgradable()]]]
  1405. [*Precondition:] The thread must have exclusive ownership of the mutex.
  1406. [*Effects:] The thread atomically releases exclusive ownership and acquires upgradable
  1407. ownership. This operation is non-blocking.
  1408. [*Throws:] An exception derived from *interprocess_exception* on error.
  1409. [blurb ['[*void unlock_and_lock_sharable()]]]
  1410. [*Precondition:] The thread must have exclusive ownership of the mutex.
  1411. [*Effects:] The thread atomically releases exclusive ownership and acquires sharable
  1412. ownership. This operation is non-blocking.
  1413. [*Throws:] An exception derived from *interprocess_exception* on error.
  1414. [blurb ['[*void unlock_upgradable_and_lock_sharable()]]]
  1415. [*Precondition:] The thread must have upgradable ownership of the mutex.
  1416. [*Effects:] The thread atomically releases upgradable ownership and acquires sharable
  1417. ownership. This operation is non-blocking.
  1418. [*Throws:] An exception derived from *interprocess_exception* on error.
  1419. [endsect]
  1420. [section:upgradable_mutexes_operations_promotions Promotions (Upgradable Mutex only)]
  1421. [blurb ['[*void unlock_upgradable_and_lock()]]]
  1422. [*Precondition:] The thread must have upgradable ownership of the mutex.
  1423. [*Effects:] The thread atomically releases upgradable ownership and acquires exclusive
  1424. ownership. This operation will block until all threads with sharable ownership release it.
  1425. [*Throws:] An exception derived from *interprocess_exception* on error.[blurb ['[*bool try_unlock_upgradable_and_lock()]]]
  1426. [*Precondition:] The thread must have upgradable ownership of the mutex.
  1427. [*Effects:] The thread atomically releases upgradable ownership and tries to acquire exclusive
  1428. ownership. This operation will fail if there are threads with sharable ownership, but
  1429. it will maintain upgradable ownership.
  1430. [*Returns:] If acquires exclusive ownership, returns true. Otherwise
  1431. returns false.
  1432. [*Throws:] An exception derived from *interprocess_exception* on error.[blurb ['[*bool timed_unlock_upgradable_and_lock(const boost::posix_time::ptime &abs_time)]]]
  1433. [*Precondition:] The thread must have upgradable ownership of the mutex.
  1434. [*Effects:] The thread atomically releases upgradable ownership and tries to acquire
  1435. exclusive ownership, waiting if necessary until abs_time. This operation will fail
  1436. if there are threads with sharable ownership or timeout reaches, but it will maintain
  1437. upgradable ownership.
  1438. [*Returns:] If acquires exclusive ownership, returns true. Otherwise
  1439. returns false.
  1440. [*Throws:] An exception derived from *interprocess_exception* on error.[blurb ['[*bool try_unlock_sharable_and_lock()]]]
  1441. [*Precondition:] The thread must have sharable ownership of the mutex.
  1442. [*Effects:] The thread atomically releases sharable ownership and tries to acquire exclusive
  1443. ownership. This operation will fail if there are threads with sharable or upgradable ownership,
  1444. but it will maintain sharable ownership.
  1445. [*Returns:] If acquires exclusive ownership, returns true. Otherwise
  1446. returns false.
  1447. [*Throws:] An exception derived from *interprocess_exception* on error.[blurb ['[*bool try_unlock_sharable_and_lock_upgradable()]]]
  1448. [*Precondition:] The thread must have sharable ownership of the mutex.
  1449. [*Effects:] The thread atomically releases sharable ownership and tries to acquire upgradable
  1450. ownership. This operation will fail if there are threads with sharable or upgradable ownership,
  1451. but it will maintain sharable ownership.
  1452. [*Returns:] If acquires upgradable ownership, returns true. Otherwise
  1453. returns false.
  1454. [*Throws:] An exception derived from *interprocess_exception* on error.
  1455. [important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
  1456. are UTC time points, not local time points]
  1457. [endsect]
  1458. [endsect]
  1459. [section:sharable_upgradable_mutexes_mutex_interprocess_mutexes Boost.Interprocess Sharable & Upgradable Mutex Types And Headers]
  1460. Boost.Interprocess offers the following sharable mutex types:
  1461. [c++]
  1462. #include <boost/interprocess/sync/interprocess_sharable_mutex.hpp>
  1463. * [classref boost::interprocess::interprocess_sharable_mutex interprocess_sharable_mutex]: A non-recursive,
  1464. anonymous sharable mutex that can be placed in shared memory or memory mapped files.
  1465. [c++]
  1466. #include <boost/interprocess/sync/named_sharable_mutex.hpp>
  1467. * [classref boost::interprocess::named_sharable_mutex named_sharable_mutex]: A non-recursive,
  1468. named sharable mutex.
  1469. Boost.Interprocess offers the following upgradable mutex types:
  1470. [c++]
  1471. #include <boost/interprocess/sync/interprocess_upgradable_mutex.hpp>
  1472. * [classref boost::interprocess::interprocess_upgradable_mutex interprocess_upgradable_mutex]: A non-recursive,
  1473. anonymous upgradable mutex that can be placed in shared memory or memory mapped files.
  1474. [c++]
  1475. #include <boost/interprocess/sync/named_upgradable_mutex.hpp>
  1476. * [classref boost::interprocess::named_upgradable_mutex named_upgradable_mutex]: A non-recursive,
  1477. named upgradable mutex.
  1478. [endsect]
  1479. [section:sharable_upgradable_locks Sharable Lock And Upgradable Lock]
  1480. As with plain mutexes, it's important to release the acquired lock even in the presence
  1481. of exceptions. [*Boost.Interprocess] mutexes are best used with the
  1482. [classref boost::interprocess::scoped_lock scoped_lock] utility,
  1483. and this class only offers exclusive locking.
  1484. As we have sharable locking and upgradable locking with upgradable mutexes, we have two new
  1485. utilities: [classref boost::interprocess::sharable_lock sharable_lock] and
  1486. [classref boost::interprocess::upgradable_lock upgradable_lock]. Both classes are similar to `scoped_lock`
  1487. but `sharable_lock` acquires the sharable lock in the constructor and `upgradable_lock`
  1488. acquires the upgradable lock in the constructor.
  1489. These two utilities can be use with any synchronization object that offers the needed
  1490. operations. For example, a user defined mutex type with no upgradable locking features
  1491. can use `sharable_lock` if the synchronization object offers [*lock_sharable()] and
  1492. [*unlock_sharable()] operations:
  1493. [section:upgradable_mutexes_lock_types Sharable Lock And Upgradable Lock Headers]
  1494. [c++]
  1495. #include <boost/interprocess/sync/sharable_lock.hpp>
  1496. [c++]
  1497. #include <boost/interprocess/sync/upgradable_lock.hpp>
  1498. [endsect]
  1499. `sharable_lock` calls [*unlock_sharable()] in its destructor, and
  1500. `upgradable_lock` calls [*unlock_upgradable()] in its destructor, so the
  1501. upgradable mutex is always unlocked when an exception occurs.
  1502. [c++]
  1503. using namespace boost::interprocess;
  1504. SharableOrUpgradableMutex sh_or_up_mutex;
  1505. {
  1506. //This will call lock_sharable()
  1507. sharable_lock<SharableOrUpgradableMutex> lock(sh_or_up_mutex);
  1508. //Some code
  1509. //The mutex will be unlocked here
  1510. }
  1511. {
  1512. //This won't lock the mutex()
  1513. sharable_lock<SharableOrUpgradableMutex> lock(sh_or_up_mutex, defer_lock);
  1514. //Lock it on demand. This will call lock_sharable()
  1515. lock.lock();
  1516. //Some code
  1517. //The mutex will be unlocked here
  1518. }
  1519. {
  1520. //This will call try_lock_sharable()
  1521. sharable_lock<SharableOrUpgradableMutex> lock(sh_or_up_mutex, try_to_lock);
  1522. //Check if the mutex has been successfully locked
  1523. if(lock){
  1524. //Some code
  1525. }
  1526. //If the mutex was locked it will be unlocked
  1527. }
  1528. {
  1529. boost::posix_time::ptime abs_time = ...
  1530. //This will call timed_lock_sharable()
  1531. scoped_lock<SharableOrUpgradableMutex> lock(sh_or_up_mutex, abs_time);
  1532. //Check if the mutex has been successfully locked
  1533. if(lock){
  1534. //Some code
  1535. }
  1536. //If the mutex was locked it will be unlocked
  1537. }
  1538. UpgradableMutex up_mutex;
  1539. {
  1540. //This will call lock_upgradable()
  1541. upgradable_lock<UpgradableMutex> lock(up_mutex);
  1542. //Some code
  1543. //The mutex will be unlocked here
  1544. }
  1545. {
  1546. //This won't lock the mutex()
  1547. upgradable_lock<UpgradableMutex> lock(up_mutex, defer_lock);
  1548. //Lock it on demand. This will call lock_upgradable()
  1549. lock.lock();
  1550. //Some code
  1551. //The mutex will be unlocked here
  1552. }
  1553. {
  1554. //This will call try_lock_upgradable()
  1555. upgradable_lock<UpgradableMutex> lock(up_mutex, try_to_lock);
  1556. //Check if the mutex has been successfully locked
  1557. if(lock){
  1558. //Some code
  1559. }
  1560. //If the mutex was locked it will be unlocked
  1561. }
  1562. {
  1563. boost::posix_time::ptime abs_time = ...
  1564. //This will call timed_lock_upgradable()
  1565. scoped_lock<UpgradableMutex> lock(up_mutex, abs_time);
  1566. //Check if the mutex has been successfully locked
  1567. if(lock){
  1568. //Some code
  1569. }
  1570. //If the mutex was locked it will be unlocked
  1571. }
  1572. [classref boost::interprocess::upgradable_lock upgradable_lock] and
  1573. [classref boost::interprocess::sharable_lock sharable_lock] offer
  1574. more features and operations, see their reference for more informations
  1575. [important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
  1576. are UTC time points, not local time points]
  1577. [endsect]
  1578. [/section:upgradable_mutexes_example Anonymous Upgradable Mutex Example]
  1579. [/import ../example/comp_doc_anonymous_upgradable_mutexA.cpp]
  1580. [/doc_anonymous_upgradable_mutexA]
  1581. [/import ../example/comp_doc_anonymous_upgradable_mutexB.cpp]
  1582. [/doc_anonymous_upgradable_mutexB]
  1583. [/endsect]
  1584. [endsect]
  1585. [section:lock_conversions Lock Transfers Through Move Semantics]
  1586. [blurb [*Interprocess uses its own move semantics emulation code for compilers
  1587. that don't support rvalues references.
  1588. This is a temporary solution until a Boost move semantics library is accepted.]]
  1589. Scoped locks and similar utilities offer simple resource management possibilities,
  1590. but with advanced mutex types like upgradable mutexes, there are operations where
  1591. an acquired lock type is released and another lock type is acquired atomically.
  1592. This is implemented by upgradable mutex operations like `unlock_and_lock_sharable()`.
  1593. These operations can be managed more effectively using [*lock transfer operations].
  1594. A lock transfer operations explicitly indicates that a mutex owned by a lock is
  1595. transferred to another lock executing atomic unlocking plus locking operations.
  1596. [section:lock_transfer_simple_transfer Simple Lock Transfer]
  1597. Imagine that a thread modifies some data in the beginning but after that, it has to
  1598. just read it in a long time. The code can acquire the exclusive lock, modify the data
  1599. and atomically release the exclusive lock and acquire the sharable lock. With these
  1600. sequence we guarantee that no other thread can modify the data in the transition
  1601. and that more readers can acquire sharable lock, increasing concurrency.
  1602. Without lock transfer operations, this would be coded like this:
  1603. [c++]
  1604. using boost::interprocess;
  1605. interprocess_upgradable_mutex mutex;
  1606. //Acquire exclusive lock
  1607. mutex.lock();
  1608. //Modify data
  1609. //Atomically release exclusive lock and acquire sharable lock.
  1610. //More threads can acquire the sharable lock and read the data.
  1611. mutex.unlock_and_lock_sharable();
  1612. //Read data
  1613. //Explicit unlocking
  1614. mutex.unlock_sharable();
  1615. This can be simple, but in the presence of exceptions, it's complicated to know
  1616. what type of lock the mutex had when the exception was thrown and what function
  1617. we should call to unlock it:
  1618. [c++]
  1619. try{
  1620. //Mutex operations
  1621. }
  1622. catch(...){
  1623. //What should we call? "unlock()" or "unlock_sharable()"
  1624. //Is the mutex locked?
  1625. }
  1626. We can use [*lock transfer] to simplify all this management:
  1627. [c++]
  1628. using boost::interprocess;
  1629. interprocess_upgradable_mutex mutex;
  1630. //Acquire exclusive lock
  1631. scoped_lock s_lock(mutex);
  1632. //Modify data
  1633. //Atomically release exclusive lock and acquire sharable lock.
  1634. //More threads can acquire the sharable lock and read the data.
  1635. sharable_lock(move(s_lock));
  1636. //Read data
  1637. //The lock is automatically unlocked calling the appropriate unlock
  1638. //function even in the presence of exceptions.
  1639. //If the mutex was not locked, no function is called.
  1640. As we can see, even if an exception is thrown at any moment, the mutex
  1641. will be automatically unlocked calling the appropriate `unlock()` or
  1642. `unlock_sharable()` method.
  1643. [endsect]
  1644. [section:lock_transfer_summary Lock Transfer Summary]
  1645. There are many lock transfer operations that we can classify according to
  1646. the operations presented in the upgradable mutex operations:
  1647. * [*Guaranteed to succeed and non-blocking:] Any transition from a more
  1648. restrictive lock to a less restrictive one. Scoped -> Upgradable,
  1649. Scoped -> Sharable, Upgradable -> Sharable.
  1650. * [*Not guaranteed to succeed:] The operation might succeed if no one has
  1651. acquired the upgradable or exclusive lock: Sharable -> Exclusive. This
  1652. operation is a try operation.
  1653. * [*Guaranteed to succeed if using an infinite waiting:] Any transition that will succeed
  1654. but needs to wait until all Sharable locks are released: Upgradable -> Scoped.
  1655. Since this is a blocking operation, we can also choose not to wait infinitely
  1656. and just try or wait until a timeout is reached.
  1657. [section:lock_transfer_summary_scoped Transfers To Scoped Lock]
  1658. Transfers to `scoped_lock` are guaranteed to succeed only from an `upgradable_lock`
  1659. and only if a blocking operation is requested, due to the fact that this operation
  1660. needs to wait until all sharable locks are released. The user can also use "try"
  1661. or "timed" transfer to avoid infinite locking, but succeed is not guaranteed.
  1662. A conversion from a `sharable_lock` is never guaranteed and thus, only a try operation
  1663. is permitted:
  1664. [c++]
  1665. //Conversions to scoped_lock
  1666. {
  1667. upgradable_lock<Mutex> u_lock(mut);
  1668. //This calls unlock_upgradable_and_lock()
  1669. scoped_lock<Mutex> e_lock(move(u_lock));
  1670. }
  1671. {
  1672. upgradable_lock<Mutex> u_lock(mut);
  1673. //This calls try_unlock_upgradable_and_lock()
  1674. scoped_lock<Mutex> e_lock(move(u_lock, try_to_lock));
  1675. }
  1676. {
  1677. boost::posix_time::ptime t = test::delay(100);
  1678. upgradable_lock<Mutex> u_lock(mut);
  1679. //This calls timed_unlock_upgradable_and_lock()
  1680. scoped_lock<Mutex> e_lock(move(u_lock));
  1681. }
  1682. {
  1683. sharable_lock<Mutex> s_lock(mut);
  1684. //This calls try_unlock_sharable_and_lock()
  1685. scoped_lock<Mutex> e_lock(move(s_lock, try_to_lock));
  1686. }
  1687. [important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
  1688. are UTC time points, not local time points]
  1689. [endsect]
  1690. [section:lock_transfer_summary_upgradable Transfers To Upgradable Lock]
  1691. A transfer to an `upgradable_lock` is guaranteed to succeed only from a `scoped_lock`
  1692. since scoped locking is a more restrictive locking than an upgradable locking. This
  1693. operation is also non-blocking.
  1694. A transfer from a `sharable_lock` is not guaranteed and only a "try" operation is permitted:
  1695. [c++]
  1696. //Conversions to upgradable
  1697. {
  1698. sharable_lock<Mutex> s_lock(mut);
  1699. //This calls try_unlock_sharable_and_lock_upgradable()
  1700. upgradable_lock<Mutex> u_lock(move(s_lock, try_to_lock));
  1701. }
  1702. {
  1703. scoped_lock<Mutex> e_lock(mut);
  1704. //This calls unlock_and_lock_upgradable()
  1705. upgradable_lock<Mutex> u_lock(move(e_lock));
  1706. }
  1707. [endsect]
  1708. [section:lock_transfer_summary_sharable Transfers To Sharable Lock]
  1709. All transfers to a `sharable_lock` are guaranteed to succeed since both
  1710. `upgradable_lock` and `scoped_lock` are more restrictive than `sharable_lock`.
  1711. These operations are also non-blocking:
  1712. [c++]
  1713. //Conversions to sharable_lock
  1714. {
  1715. upgradable_lock<Mutex> u_lock(mut);
  1716. //This calls unlock_upgradable_and_lock_sharable()
  1717. sharable_lock<Mutex> s_lock(move(u_lock));
  1718. }
  1719. {
  1720. scoped_lock<Mutex> e_lock(mut);
  1721. //This calls unlock_and_lock_sharable()
  1722. sharable_lock<Mutex> s_lock(move(e_lock));
  1723. }
  1724. [endsect]
  1725. [endsect]
  1726. [section:lock_transfer_not_locked Transferring Unlocked Locks]
  1727. In the previous examples, the mutex used in the transfer operation was previously
  1728. locked:
  1729. [c++]
  1730. Mutex mut;
  1731. //This calls mut.lock()
  1732. scoped_lock<Mutex> e_lock(mut);
  1733. //This calls unlock_and_lock_sharable()
  1734. sharable_lock<Mutex> s_lock(move(e_lock));
  1735. }
  1736. but it's possible to execute the transfer with an unlocked source, due to explicit
  1737. unlocking, a try, timed or a `defer_lock` constructor:
  1738. [c++]
  1739. //These operations can leave the mutex unlocked!
  1740. {
  1741. //Try might fail
  1742. scoped_lock<Mutex> e_lock(mut, try_to_lock);
  1743. sharable_lock<Mutex> s_lock(move(e_lock));
  1744. }
  1745. {
  1746. //Timed operation might fail
  1747. scoped_lock<Mutex> e_lock(mut, time);
  1748. sharable_lock<Mutex> s_lock(move(e_lock));
  1749. }
  1750. {
  1751. //Avoid mutex locking
  1752. scoped_lock<Mutex> e_lock(mut, defer_lock);
  1753. sharable_lock<Mutex> s_lock(move(e_lock));
  1754. }
  1755. {
  1756. //Explicitly call unlock
  1757. scoped_lock<Mutex> e_lock(mut);
  1758. e_lock.unlock();
  1759. //Mutex was explicitly unlocked
  1760. sharable_lock<Mutex> s_lock(move(e_lock));
  1761. }
  1762. If the source mutex was not locked:
  1763. * The target lock does not execute the atomic `unlock_xxx_and_lock_xxx` operation.
  1764. * The target lock is also unlocked.
  1765. * The source lock is released() and the ownership of the mutex is transferred to the target.
  1766. [c++]
  1767. {
  1768. scoped_lock<Mutex> e_lock(mut, defer_lock);
  1769. sharable_lock<Mutex> s_lock(move(e_lock));
  1770. //Assertions
  1771. assert(e_lock.mutex() == 0);
  1772. assert(s_lock.mutex() != 0);
  1773. assert(e_lock.owns() == false);
  1774. }
  1775. [endsect]
  1776. [section:lock_transfer_failure Transfer Failures]
  1777. When executing a lock transfer, the operation can fail:
  1778. * The executed atomic mutex unlock plus lock function might throw.
  1779. * The executed atomic function might be a "try" or "timed" function that can fail.
  1780. In the first case, the mutex ownership is not transferred and the source lock's
  1781. destructor will unlock the mutex:
  1782. [c++]
  1783. {
  1784. scoped_lock<Mutex> e_lock(mut, defer_lock);
  1785. //This operations throws because
  1786. //"unlock_and_lock_sharable()" throws!!!
  1787. sharable_lock<Mutex> s_lock(move(e_lock));
  1788. //Some code ...
  1789. //e_lock's destructor will call "unlock()"
  1790. }
  1791. In the second case, if an internal "try" or "timed" operation fails (returns "false")
  1792. then the mutex ownership is [*not] transferred, the source lock is unchanged and the target
  1793. lock's state will the same as a default construction:
  1794. [c++]
  1795. {
  1796. sharable_lock<Mutex> s_lock(mut);
  1797. //Internal "try_unlock_sharable_and_lock_upgradable()" returns false
  1798. upgradable_lock<Mutex> u_lock(move(s_lock, try_to_lock));
  1799. assert(s_lock.mutex() == &mut);
  1800. assert(s_lock.owns() == true);
  1801. assert(u_lock.mutex() == 0);
  1802. assert(u_lock.owns() == false);
  1803. //u_lock's destructor does nothing
  1804. //s_lock's destructor calls "unlock()"
  1805. }
  1806. [endsect]
  1807. [endsect]
  1808. [section:file_lock File Locks]
  1809. [section:file_lock_whats_a_file_lock What's A File Lock?]
  1810. A file lock is an interprocess synchronization mechanism to protect concurrent
  1811. writes and reads to files using a mutex ['embedded] in the file. This ['embedded mutex]
  1812. has sharable and exclusive locking capabilities.
  1813. With a file lock, an existing file can be used as a mutex without the need
  1814. of creating additional synchronization objects to control concurrent file
  1815. reads or writes.
  1816. Generally speaking, we can have two file locking capabilities:
  1817. * [*Advisory locking:] The operating system kernel maintains a list of files that
  1818. have been locked. But does not prevent writing to those files even if a process
  1819. has acquired a sharable lock or does not prevent reading from the file when a process
  1820. has acquired the exclusive lock. Any process can ignore an advisory lock.
  1821. This means that advisory locks are for [*cooperating] processes,
  1822. processes that can trust each other. This is similar to a mutex protecting data
  1823. in a shared memory segment: any process connected to that memory can overwrite the
  1824. data but [*cooperative] processes use mutexes to protect the data first acquiring
  1825. the mutex lock.
  1826. * [*Mandatory locking:] The OS kernel checks every read and write request to verify
  1827. that the operation can be performed according to the acquired lock. Reads and writes
  1828. block until the lock is released.
  1829. [*Boost.Interprocess] implements [*advisory blocking] because of portability reasons.
  1830. This means that every process accessing to a file concurrently, must cooperate using
  1831. file locks to synchronize the access.
  1832. In some systems file locking can be even further refined, leading to [*record locking],
  1833. where a user can specify a [*byte range] within the file where the lock is applied.
  1834. This allows concurrent write access by several processes if they need to access a
  1835. different byte range in the file. [*Boost.Interprocess] does [*not] offer record
  1836. locking for the moment, but might offer it in the future. To use a file lock just
  1837. include:
  1838. [c++]
  1839. #include <boost/interprocess/sync/file_lock.hpp>
  1840. A file locking is a class that has [*process lifetime]. This means that if a process
  1841. holding a file lock ends or crashes, the operating system will automatically unlock
  1842. it. This feature is very useful in some situations where we want to assure
  1843. automatic unlocking even when the process crashes and avoid leaving blocked resources
  1844. in the system. A file lock is constructed using the name of the file as an argument:
  1845. [c++]
  1846. #include <boost/interprocess/sync/file_lock.hpp>
  1847. int main()
  1848. {
  1849. //This throws if the file does not exist or it can't
  1850. //open it with read-write access!
  1851. boost::interprocess::file_lock flock("my_file");
  1852. return 0;
  1853. }
  1854. [endsect]
  1855. [section:file_lock_operations File Locking Operations]
  1856. File locking has normal mutex operations plus sharable locking capabilities.
  1857. This means that we can have multiple readers holding the sharable lock and
  1858. writers holding the exclusive lock waiting until the readers end their job.
  1859. However, file locking does [*not] support upgradable locking or promotion or
  1860. demotion (lock transfers), so it's more limited than an upgradable lock.
  1861. These are the operations:
  1862. [blurb ['[*void lock()]]]
  1863. [*Effects:]
  1864. The calling thread tries to obtain exclusive ownership of the file lock, and if
  1865. another thread has exclusive or sharable ownership of the mutex,
  1866. it waits until it can obtain the ownership.
  1867. [*Throws:] *interprocess_exception* on error.
  1868. [blurb ['[*bool try_lock()]]]
  1869. [*Effects:]
  1870. The calling thread tries to acquire exclusive ownership of the file lock
  1871. without waiting. If no other thread has exclusive or sharable ownership of
  1872. the file lock, this succeeds.
  1873. [*Returns:] If it can acquire exclusive ownership immediately returns true.
  1874. If it has to wait, returns false.
  1875. [*Throws:] *interprocess_exception* on error.
  1876. [blurb ['[*bool timed_lock(const boost::posix_time::ptime &abs_time)]]]
  1877. [*Effects:]
  1878. The calling thread tries to acquire exclusive ownership of the file lock
  1879. waiting if necessary until no other thread has exclusive or
  1880. sharable ownership of the file lock or abs_time is reached.
  1881. [*Returns:] If acquires exclusive ownership, returns true. Otherwise
  1882. returns false.
  1883. [*Throws:] *interprocess_exception* on error.
  1884. [blurb ['[*void unlock()]]]
  1885. [*Precondition:] The thread must have exclusive ownership of the file lock.
  1886. [*Effects:] The calling thread releases the exclusive ownership of the file lock.
  1887. [*Throws:] An exception derived from *interprocess_exception* on error.
  1888. [blurb ['[*void lock_sharable()]]]
  1889. [*Effects:]
  1890. The calling thread tries to obtain sharable ownership of the file lock,
  1891. and if another thread has exclusive ownership of the file lock,
  1892. waits until it can obtain the ownership.
  1893. [*Throws:] *interprocess_exception* on error.
  1894. [blurb ['[*bool try_lock_sharable()]]]
  1895. [*Effects:]
  1896. The calling thread tries to acquire sharable ownership of the file
  1897. lock without waiting. If no other thread has exclusive ownership of
  1898. the file lock, this succeeds.
  1899. [*Returns:] If it can acquire sharable ownership immediately returns true.
  1900. If it has to wait, returns false.
  1901. [*Throws:] *interprocess_exception* on error.
  1902. [blurb ['[*bool timed_lock_sharable(const boost::posix_time::ptime &abs_time)]]]
  1903. [*Effects:]
  1904. The calling thread tries to acquire sharable ownership of the file lock
  1905. waiting if necessary until no other thread has exclusive
  1906. ownership of the file lock or abs_time is reached.
  1907. [*Returns:] If acquires sharable ownership, returns true. Otherwise
  1908. returns false.
  1909. [*Throws:] *interprocess_exception* on error.
  1910. [blurb ['[*void unlock_sharable()]]]
  1911. [*Precondition:] The thread must have sharable ownership of the file lock.
  1912. [*Effects:] The calling thread releases the sharable ownership of the file lock.
  1913. [*Throws:] An exception derived from *interprocess_exception* on error.
  1914. For more file locking methods, please
  1915. [classref boost::interprocess::file_lock file_lock reference].
  1916. [important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
  1917. are UTC time points, not local time points]
  1918. [endsect]
  1919. [section:file_lock_scoped_locks Scoped Lock and Sharable Lock With File Locking]
  1920. [classref boost::interprocess::scoped_lock scoped_lock] and
  1921. [classref boost::interprocess::sharable_lock sharable_lock] can be used to make
  1922. file locking easier in the presence of exceptions, just like with mutexes:
  1923. [c++]
  1924. #include <boost/interprocess/sync/file_lock.hpp>
  1925. #include <boost/interprocess/sync/sharable_lock.hpp>
  1926. //...
  1927. using namespace boost::interprocess;
  1928. //This process reads the file
  1929. // ...
  1930. //Open the file lock
  1931. file_lock f_lock("my_file");
  1932. {
  1933. //Construct a sharable lock with the file lock.
  1934. //This will call "f_lock.sharable_lock()".
  1935. sharable_lock<file_lock> sh_lock(f_lock);
  1936. //Now read the file...
  1937. //The sharable lock is automatically released by
  1938. //sh_lock's destructor
  1939. }
  1940. [c++]
  1941. #include <boost/interprocess/sync/file_lock.hpp>
  1942. #include <boost/interprocess/sync/scoped_lock.hpp>
  1943. //...
  1944. using namespace boost::interprocess;
  1945. //This process writes the file
  1946. // ...
  1947. //Open the file lock
  1948. file_lock f_lock("my_file");
  1949. {
  1950. //Construct an exclusive lock with the file lock.
  1951. //This will call "f_lock.lock()".
  1952. scoped_lock<file_lock> e_lock(f_lock);
  1953. //Now write the file...
  1954. //The exclusive lock is automatically released by
  1955. //e_lock's destructor
  1956. }
  1957. However, lock transfers are only allowed between same type of locks, that is,
  1958. from a sharable lock to another sharable lock or from a scoped lock to another
  1959. scoped lock. A transfer from a scoped lock to a sharable lock is not allowed,
  1960. because [classref boost::interprocess::file_lock file_lock] has no lock
  1961. promotion or demotion functions like `unlock_and_lock_sharable()`.
  1962. This will produce a compilation error:
  1963. [c++]
  1964. //Open the file lock
  1965. file_lock f_lock("my_file");
  1966. scoped_lock<file_lock> e_lock(f_lock);
  1967. //Compilation error, f_lock has no "unlock_and_lock_sharable()" member!
  1968. sharable_lock<file_lock> e_lock(move(f_lock));
  1969. [endsect]
  1970. [section:file_lock_not_thread_safe Caution: Synchronization limitations]
  1971. If you plan to use file locks just like named mutexes, be careful, because portable
  1972. file locks have synchronization limitations, mainly because different implementations
  1973. (POSIX, Windows) offer different guarantees. Interprocess file locks have the following
  1974. limitations:
  1975. * It's unspecified if a `file_lock` synchronizes [*two threads from the same process].
  1976. * It's unspecified if a process can use two `file_lock` objects pointing to the same file.
  1977. The first limitation comes mainly from POSIX, since a file handle is a per-process attribute
  1978. and not a per-thread attribute. This means that if a thread uses a `file_lock` object to lock
  1979. a file, other threads will see the file as locked.
  1980. Windows file locking mechanism, on the other hand, offer thread-synchronization guarantees
  1981. so a thread trying to lock the already locked file, would block.
  1982. The second limitation comes from the fact that file locking synchronization state
  1983. is tied with a single file descriptor in Windows. This means that if two `file_lock`
  1984. objects are created pointing to the same file, no synchronization is guaranteed. In
  1985. POSIX, when two file descriptors are used to lock a file if a descriptor is closed,
  1986. all file locks set by the calling process are cleared.
  1987. To sum up, if you plan to use portable file locking in your processes, use the following
  1988. restrictions:
  1989. * [*For each file, use a single `file_lock` object per process.]
  1990. * [*Use the same thread to lock and unlock a file.]
  1991. * If you are using a std::fstream/native file handle to write to the file
  1992. while using file locks on that file, [*don't close the file before
  1993. releasing all the locks of the file.]
  1994. [endsect]
  1995. [section:file_lock_careful_iostream Be Careful With Iostream Writing]
  1996. As we've seen file locking can be useful to synchronize two processes,
  1997. but [*make sure data is written to the file]
  1998. before unlocking the file lock. Take in care that iostream classes do some
  1999. kind of buffering, so if you want to make sure that other processes can
  2000. see the data you've written, you have the following alternatives:
  2001. * Use native file functions (read()/write() in Unix systems and ReadFile/WriteFile
  2002. in Windows systems) instead of iostream.
  2003. * Flush data before unlocking the file lock in writers using `fflush` if you are using
  2004. standard C functions or the `flush()` member function when using C++ iostreams. In windows
  2005. you can't even use another class to access the same file.
  2006. //...
  2007. using namespace boost::interprocess;
  2008. //This process writes the file
  2009. // ...
  2010. //Open the file lock
  2011. fstream file("my_file")
  2012. file_lock f_lock("my_lock_file");
  2013. {
  2014. scoped_lock<file_lock> e_lock(f_lock);
  2015. //Now write the file...
  2016. //Flush data before unlocking the exclusive lock
  2017. file.flush();
  2018. }
  2019. [endsect]
  2020. [endsect]
  2021. [section:message_queue Message Queue]
  2022. [section:message_queue_whats_a_mq What's A Message Queue?]
  2023. A message queue is similar to a list of messages. Threads can put messages
  2024. in the queue and they can also remove messages from the queue. Each message
  2025. can have also a [*priority] so that higher priority messages are read before
  2026. lower priority messages. Each message has some attributes:
  2027. * A priority.
  2028. * The length of the message.
  2029. * The data (if length is bigger than 0).
  2030. A thread can send a message to or receive a message from the message
  2031. queue using 3 methods:
  2032. * [*Blocking]: If the message queue is full when sending or the message queue
  2033. is empty when receiving, the thread is blocked until there
  2034. is room for a new message or there is a new message.
  2035. * [*Try]: If the message queue is full when sending or the message queue is empty
  2036. when receiving, the thread returns immediately with an error.
  2037. * [*Timed]: If the message queue is full when sending or the message queue is empty
  2038. when receiving, the thread retries the operation until succeeds (returning
  2039. successful state) or a timeout is reached (returning a failure).
  2040. A message queue [*just copies raw bytes between processes] and does not send
  2041. objects. This means that if we want to send an object using a message queue
  2042. [*the object must be binary serializable]. For example, we can send integers
  2043. between processes but [*not] a `std::string`. You should use [*Boost.Serialization]
  2044. or use advanced [*Boost.Interprocess] mechanisms to send complex data between
  2045. processes.
  2046. The [*Boost.Interprocess] message queue is a named interprocess communication: the
  2047. message queue is created with a name and it's opened with a name, just like a file.
  2048. When creating a message queue, the user must specify the maximum message size and
  2049. the maximum message number that the message queue can store. These parameters will
  2050. define the resources (for example the size of the shared memory used to implement
  2051. the message queue if shared memory is used).
  2052. [c++]
  2053. using boost::interprocess;
  2054. //Create a message_queue. If the queue
  2055. //exists throws an exception
  2056. message_queue mq
  2057. (create_only //only create
  2058. ,"message_queue" //name
  2059. ,100 //max message number
  2060. ,100 //max message size
  2061. );
  2062. [c++]
  2063. using boost::interprocess;
  2064. //Creates or opens a message_queue. If the queue
  2065. //does not exist creates it, otherwise opens it.
  2066. //Message number and size are ignored if the queue
  2067. //is opened
  2068. message_queue mq
  2069. (open_or_create //open or create
  2070. ,"message_queue" //name
  2071. ,100 //max message number
  2072. ,100 //max message size
  2073. );
  2074. [c++]
  2075. using boost::interprocess;
  2076. //Opens a message_queue. If the queue
  2077. //does not exist throws an exception.
  2078. message_queue mq
  2079. (open_only //only open
  2080. ,"message_queue" //name
  2081. );
  2082. The message queue is explicitly removed calling the static `remove` function:
  2083. [c++]
  2084. using boost::interprocess;
  2085. message_queue::remove("message_queue");
  2086. The function can fail if the message queue is still being used by any process.
  2087. [endsect]
  2088. [section:message_queue_example Using a message queue]
  2089. To use a message queue you must include the following header:
  2090. [c++]
  2091. #include <boost/interprocess/ipc/message_queue.hpp>
  2092. In the following example, the first process creates the message queue, and writes
  2093. an array of integers on it. The other process just reads the array and checks that
  2094. the sequence number is correct. This is the first process:
  2095. [import ../example/comp_doc_message_queueA.cpp]
  2096. [doc_message_queueA]
  2097. This is the second process:
  2098. [import ../example/comp_doc_message_queueB.cpp]
  2099. [doc_message_queueB]
  2100. To know more about this class and all its operations, please see the
  2101. [classref boost::interprocess::message_queue message_queue] class reference.
  2102. [endsect]
  2103. [endsect]
  2104. [endsect]
  2105. [section:managed_memory_segments Managed Memory Segments]
  2106. [section:making_ipc_easy Making Interprocess Data Communication Easy]
  2107. [section:managed_memory_segments_intro Introduction]
  2108. As we have seen, [*Boost.Interprocess] offers some basic classes to create shared memory
  2109. objects and file mappings and map those mappable classes to the process' address space.
  2110. However, managing those memory segments is not not easy for non-trivial tasks.
  2111. A mapped region is a fixed-length memory buffer and creating and destroying objects
  2112. of any type dynamically, requires a lot of work, since it would require programming
  2113. a memory management algorithm to allocate portions of that segment.
  2114. Many times, we also want to associate names to objects created in shared memory, so
  2115. all the processes can find the object using the name.
  2116. [*Boost.Interprocess] offers 4 managed memory segment classes:
  2117. * To manage a shared memory mapped region ([*basic_managed_shared_memory] class).
  2118. * To manage a memory mapped file ([*basic_managed_mapped_file]).
  2119. * To manage a heap allocated (`operator new`) memory buffer ([*basic_managed_heap_memory] class).
  2120. * To manage a user provided fixed size buffer ([*basic_managed_external_buffer] class).
  2121. The first two classes manage memory segments that can be shared between processes. The
  2122. third is useful to create complex data-bases to be sent though other mechanisms like
  2123. message queues to other processes. The fourth class can manage any fixed size memory
  2124. buffer. The first two classes will be explained in the next two sections.
  2125. [*basic_managed_heap_memory] and [*basic_managed_external_buffer] will be explained later.
  2126. The most important services of a managed memory segment are:
  2127. * Dynamic allocation of portions of a memory the segment.
  2128. * Construction of C++ objects in the memory segment. These objects can be anonymous
  2129. or we can associate a name to them.
  2130. * Searching capabilities for named objects.
  2131. * Customization of many features: memory allocation algorithm, index types or
  2132. character types.
  2133. * Atomic constructions and destructions so that if the segment is shared between
  2134. two processes it's impossible to create two objects associated with the same
  2135. name, simplifying synchronization.
  2136. [endsect]
  2137. [section:managed_memory_segment_int Declaration of managed memory segment classes]
  2138. All [*Boost.Interprocess] managed memory segment classes are templatized classes
  2139. that can be customized by the user:
  2140. [c++]
  2141. template
  2142. <
  2143. class CharType,
  2144. class MemoryAlgorithm,
  2145. template<class IndexConfig> class IndexType
  2146. >
  2147. class basic_managed_shared_memory / basic_managed_mapped_file /
  2148. basic_managed_heap_memory / basic_external_buffer;
  2149. These classes can be customized with the following template parameters:
  2150. * *CharType* is the type of the character that will be used to identify
  2151. the created named objects (for example, *char* or *wchar_t*)
  2152. * *MemoryAlgorithm* is the memory algorithm used to allocate portions of the
  2153. segment (for example, rbtree_best_fit ). The internal typedefs of the
  2154. memory algorithm also define:
  2155. * The synchronization type (`MemoryAlgorithm::mutex_family`) to be used
  2156. in all allocation operations.
  2157. This allows the use of user-defined mutexes or avoiding internal
  2158. locking (maybe code will be externally synchronized by the user).
  2159. * The Pointer type (`MemoryAlgorithm::void_pointer`) to be used
  2160. by the memory allocation algorithm or additional helper structures
  2161. (like a map to maintain object/name associations). All STL compatible
  2162. allocators and containers to be used with this managed memory segment
  2163. will use this pointer type. The pointer type
  2164. will define if the managed memory segment can be mapped between
  2165. several processes. For example, if `void_pointer` is `offset_ptr<void>`
  2166. we will be able to map the managed segment in different base
  2167. addresses in each process. If `void_pointer` is `void*` only fixed
  2168. address mapping could be used.
  2169. * See [link interprocess.customizing_interprocess.custom_interprocess_alloc Writing a new memory
  2170. allocation algorithm] for more details about memory algorithms.
  2171. * *IndexType* is the type of index that will be used to store the name-object
  2172. association (for example, a map, a hash-map, or an ordered vector).
  2173. This way, we can use `char` or `wchar_t` strings to identify created C++
  2174. objects in the memory segment, we can plug new shared memory allocation
  2175. algorithms, and use the index type that is best suited to our needs.
  2176. [endsect]
  2177. [endsect]
  2178. [section:managed_shared_memory Managed Shared Memory]
  2179. [section:managed_memory_common_shm Common Managed Shared Memory Classes]
  2180. As seen, *basic_managed_shared_memory* offers a great variety of customization. But
  2181. for the average user, a common, default shared memory named object creation is needed.
  2182. Because of this, [*Boost.Interprocess] defines the most common managed shared memory
  2183. specializations:
  2184. [c++]
  2185. //!Defines a managed shared memory with c-strings as keys for named objects,
  2186. //!the default memory algorithm (with process-shared mutexes,
  2187. //!and offset_ptr as internal pointers) as memory allocation algorithm
  2188. //!and the default index type as the index.
  2189. //!This class allows the shared memory to be mapped in different base
  2190. //!in different processes
  2191. typedef
  2192. basic_managed_shared_memory<char
  2193. ,/*Default memory algorithm defining offset_ptr<void> as void_pointer*/
  2194. ,/*Default index type*/>
  2195. managed_shared_memory;
  2196. //!Defines a managed shared memory with wide strings as keys for named objects,
  2197. //!the default memory algorithm (with process-shared mutexes,
  2198. //!and offset_ptr as internal pointers) as memory allocation algorithm
  2199. //!and the default index type as the index.
  2200. //!This class allows the shared memory to be mapped in different base
  2201. //!in different processes
  2202. typedef
  2203. basic_managed_shared_memory<wchar_t
  2204. ,/*Default memory algorithm defining offset_ptr<void> as void_pointer*/
  2205. ,/*Default index type*/>
  2206. wmanaged_shared_memory;
  2207. `managed_shared_memory` allocates objects in shared memory associated with a c-string and
  2208. `wmanaged_shared_memory` allocates objects in shared memory associated with a wchar_t null
  2209. terminated string. Both define the pointer type as `offset_ptr<void>` so they can be
  2210. used to map the shared memory at different base addresses in different processes.
  2211. If the user wants to map the shared memory in the same address in all processes and
  2212. want to use raw pointers internally instead of offset pointers, [*Boost.Interprocess]
  2213. defines the following types:
  2214. [c++]
  2215. //!Defines a managed shared memory with c-strings as keys for named objects,
  2216. //!the default memory algorithm (with process-shared mutexes,
  2217. //!and offset_ptr as internal pointers) as memory allocation algorithm
  2218. //!and the default index type as the index.
  2219. //!This class allows the shared memory to be mapped in different base
  2220. //!in different processes*/
  2221. typedef basic_managed_shared_memory
  2222. <char
  2223. ,/*Default memory algorithm defining void * as void_pointer*/
  2224. ,/*Default index type*/>
  2225. fixed_managed_shared_memory;
  2226. //!Defines a managed shared memory with wide strings as keys for named objects,
  2227. //!the default memory algorithm (with process-shared mutexes,
  2228. //!and offset_ptr as internal pointers) as memory allocation algorithm
  2229. //!and the default index type as the index.
  2230. //!This class allows the shared memory to be mapped in different base
  2231. //!in different processes
  2232. typedef basic_managed_shared_memory
  2233. <wchar_t
  2234. ,/*Default memory algorithm defining void * as void_pointer*/
  2235. ,/*Default index type*/>
  2236. wfixed_managed_shared_memory;
  2237. [endsect]
  2238. [section:constructing_managed_shared_memories Constructing Managed Shared Memory]
  2239. Managed shared memory is an advanced class that combines a shared memory object
  2240. and a mapped region that covers all the shared memory object. That means that
  2241. when we [*create] a new managed shared memory:
  2242. * A new shared memory object is created.
  2243. * The whole shared memory object is mapped in the process' address space.
  2244. * Some helper objects are constructed (name-object index, internal synchronization
  2245. objects, internal variables...) in the mapped region to implement
  2246. managed memory segment features.
  2247. When we [*open] a managed shared memory
  2248. * A shared memory object is opened.
  2249. * The whole shared memory object is mapped in the process' address space.
  2250. To use a managed shared memory, you must include the following header:
  2251. [c++]
  2252. #include <boost/interprocess/managed_shared_memory.hpp>
  2253. [c++]
  2254. //1. Creates a new shared memory object
  2255. // called "MySharedMemory".
  2256. //2. Maps the whole object to this
  2257. // process' address space.
  2258. //3. Constructs some objects in shared memory
  2259. // to implement managed features.
  2260. //!! If anything fails, throws interprocess_exception
  2261. //
  2262. managed_shared_memory segment ( create_only
  2263. , "MySharedMemory" //Shared memory object name
  2264. , 65536); //Shared memory object size in bytes
  2265. [c++]
  2266. //1. Opens a shared memory object
  2267. // called "MySharedMemory".
  2268. //2. Maps the whole object to this
  2269. // process' address space.
  2270. //3. Obtains pointers to constructed internal objects
  2271. // to implement managed features.
  2272. //!! If anything fails, throws interprocess_exception
  2273. //
  2274. managed_shared_memory segment (open_only, "MySharedMemory");//Shared memory object name
  2275. [c++]
  2276. //1. If the segment was previously created
  2277. // equivalent to "open_only" (size is ignored).
  2278. //2. Otherwise, equivalent to "create_only"
  2279. //!! If anything fails, throws interprocess_exception
  2280. //
  2281. managed_shared_memory segment ( open_or_create
  2282. , "MySharedMemory" //Shared memory object name
  2283. , 65536); //Shared memory object size in bytes
  2284. When the `managed_shared_memory` object is destroyed, the shared memory
  2285. object is automatically unmapped, and all the resources are freed. To remove
  2286. the shared memory object from the system you must use the `shared_memory_object::remove`
  2287. function. Shared memory object removing might fail if any
  2288. process still has the shared memory object mapped.
  2289. The user can also map the managed shared memory in a fixed address. This option is
  2290. essential when using using `fixed_managed_shared_memory`. To do this, just
  2291. add the mapping address as an extra parameter:
  2292. [c++]
  2293. fixed_managed_shared_memory segment (open_only ,"MyFixedAddressSharedMemory" //Shared memory object name
  2294. ,(void*)0x30000000 //Mapping address
  2295. [endsect]
  2296. [section:windows_managed_memory_common_shm Using native windows shared memory]
  2297. Windows users might also want to use native windows shared memory instead of
  2298. the portable [classref boost::interprocess::shared_memory_object shared_memory_object]
  2299. managed memory. This is achieved through the
  2300. [classref boost::interprocess::basic_managed_windows_shared_memory basic_managed_windows_shared_memory]
  2301. class. To use it just include:
  2302. [c++]
  2303. #include <boost/interprocess/managed_windows_shared_memory.hpp>
  2304. This class has the same interface as
  2305. [classref boost::interprocess::basic_managed_shared_memory basic_managed_shared_memory]
  2306. but uses native windows shared memory. Note that this managed class has the same
  2307. lifetime issues as the windows shared memory: when the last process attached to the
  2308. windows shared memory is detached from the memory (or ends/crashes) the memory is
  2309. destroyed. So there is no persistence support for windows shared memory.
  2310. To communicate between system services and user applications using `managed_windows_shared_memory`,
  2311. please read the explanations given in chapter
  2312. [link interprocess.sharedmemorybetweenprocesses.sharedmemory.windows_shared_memory Native windows shared memory].
  2313. [endsect]
  2314. [section:xsi_managed_memory_common_shm Using XSI (system V) shared memory]
  2315. Unix users might also want to use XSI (system V) instead of
  2316. the portable [classref boost::interprocess::shared_memory_object shared_memory_object]
  2317. managed memory. This is achieved through the
  2318. [classref boost::interprocess::basic_managed_xsi_shared_memory basic_managed_xsi_shared_memory]
  2319. class. To use it just include:
  2320. [c++]
  2321. #include <boost/interprocess/managed_xsi_shared_memory.hpp>
  2322. This class has nearly the same interface as
  2323. [classref boost::interprocess::basic_managed_shared_memory basic_managed_shared_memory]
  2324. but uses XSI shared memory as backend.
  2325. [endsect]
  2326. For more information about managed XSI shared memory capabilities, see
  2327. [classref boost::interprocess::basic_managed_xsi_shared_memory basic_managed_xsi_shared_memory] class reference.
  2328. [endsect]
  2329. [section:managed_mapped_files Managed Mapped File]
  2330. [section:managed_memory_common_mfile Common Managed Mapped Files]
  2331. As seen, *basic_managed_mapped_file* offers a great variety of customization. But
  2332. for the average user, a common, default shared memory named object creation is needed.
  2333. Because of this, [*Boost.Interprocess] defines the most common managed mapped file
  2334. specializations:
  2335. [c++]
  2336. //Named object creation managed memory segment
  2337. //All objects are constructed in the memory-mapped file
  2338. // Names are c-strings,
  2339. // Default memory management algorithm(rbtree_best_fit with no mutexes)
  2340. // Name-object mappings are stored in the default index type (flat_map)
  2341. typedef basic_managed_mapped_file <
  2342. char,
  2343. rbtree_best_fit<mutex_family, offset_ptr<void> >,
  2344. flat_map_index
  2345. > managed_mapped_file;
  2346. //Named object creation managed memory segment
  2347. //All objects are constructed in the memory-mapped file
  2348. // Names are wide-strings,
  2349. // Default memory management algorithm(rbtree_best_fit with no mutexes)
  2350. // Name-object mappings are stored in the default index type (flat_map)
  2351. typedef basic_managed_mapped_file<
  2352. wchar_t,
  2353. rbtree_best_fit<mutex_family, offset_ptr<void> >,
  2354. flat_map_index
  2355. > wmanaged_mapped_file;
  2356. `managed_mapped_file` allocates objects in a memory mapped files associated with a c-string
  2357. and `wmanaged_mapped_file` allocates objects in a memory mapped file associated with a wchar_t null
  2358. terminated string. Both define the pointer type as `offset_ptr<void>` so they can be
  2359. used to map the file at different base addresses in different processes.
  2360. [endsect]
  2361. [section:constructing_managed_mapped_files Constructing Managed Mapped Files]
  2362. Managed mapped file is an advanced class that combines a file
  2363. and a mapped region that covers all the file. That means that
  2364. when we [*create] a new managed mapped file:
  2365. * A new file is created.
  2366. * The whole file is mapped in the process' address space.
  2367. * Some helper objects are constructed (name-object index, internal synchronization
  2368. objects, internal variables...) in the mapped region to implement
  2369. managed memory segment features.
  2370. When we [*open] a managed mapped file
  2371. * A file is opened.
  2372. * The whole file is mapped in the process' address space.
  2373. To use a managed mapped file, you must include the following header:
  2374. [c++]
  2375. #include <boost/interprocess/managed_mapped_file.hpp>
  2376. [c++]
  2377. //1. Creates a new file
  2378. // called "MyMappedFile".
  2379. //2. Maps the whole file to this
  2380. // process' address space.
  2381. //3. Constructs some objects in the memory mapped
  2382. // file to implement managed features.
  2383. //!! If anything fails, throws interprocess_exception
  2384. //
  2385. managed_mapped_file mfile ( create_only
  2386. , "MyMappedFile" //Mapped file name
  2387. , 65536); //Mapped file size
  2388. [c++]
  2389. //1. Opens a file
  2390. // called "MyMappedFile".
  2391. //2. Maps the whole file to this
  2392. // process' address space.
  2393. //3. Obtains pointers to constructed internal objects
  2394. // to implement managed features.
  2395. //!! If anything fails, throws interprocess_exception
  2396. //
  2397. managed_mapped_file mfile ( open_only
  2398. , "MyMappedFile"); //Mapped file name
  2399. [c++]
  2400. //1. If the file was previously created
  2401. // equivalent to "open_only".
  2402. //2. Otherwise, equivalent to "open_only" (size is ignored)
  2403. //
  2404. //!! If anything fails, throws interprocess_exception
  2405. //
  2406. managed_mapped_file mfile (open_or_create
  2407. , "MyMappedFile" //Mapped file name
  2408. , 65536); //Mapped file size
  2409. When the `managed_mapped_file` object is destroyed, the file is
  2410. automatically unmapped, and all the resources are freed. To remove
  2411. the file from the filesystem you could use standard C `std::remove`
  2412. or [*Boost.Filesystem]'s `remove()` functions, but file removing might fail
  2413. if any process still has the file mapped in memory or the file is open
  2414. by any process.
  2415. To obtain a more portable behaviour, use `file_mapping::remove(const char *)` operation, which
  2416. will remove the file even if it's being mapped. However, removal will fail in some OS systems if
  2417. the file (eg. by C++ file streams) and no delete share permission was granted to the file. But in
  2418. most common cases `file_mapping::remove` is portable enough.
  2419. [endsect]
  2420. For more information about managed mapped file capabilities, see
  2421. [classref boost::interprocess::basic_managed_mapped_file basic_managed_mapped_file] class reference.
  2422. [endsect]
  2423. [section:managed_memory_segment_features Managed Memory Segment Features]
  2424. The following features are common to all managed memory segment classes, but
  2425. we will use managed shared memory in our examples. We can do the same with
  2426. memory mapped files or other managed memory segment classes.
  2427. [section:allocate_deallocate Allocating fragments of a managed memory segment]
  2428. If a basic raw-byte allocation is needed from a managed memory
  2429. segment, (for example, a managed shared memory), to implement
  2430. top-level interprocess communications, this class offers
  2431. [*allocate] and [*deallocate] functions. The allocation function
  2432. comes with throwing and no throwing versions. Throwing version throws
  2433. boost::interprocess::bad_alloc (which derives from `std::bad_alloc`)
  2434. if there is no more memory and the non-throwing version returns 0 pointer.
  2435. [import ../example/doc_managed_raw_allocation.cpp]
  2436. [doc_managed_raw_allocation]
  2437. [endsect]
  2438. [section:segment_offset Obtaining handles to identify data]
  2439. The class also offers conversions between absolute addresses that belong to
  2440. a managed memory segment and a handle that can be passed using any
  2441. interprocess mechanism. That handle can be transformed again to an absolute
  2442. address using a managed memory segment that also contains that object.
  2443. Handles can be used as keys between processes to identify allocated portions
  2444. of a managed memory segment or objects constructed in the managed segment.
  2445. [c++]
  2446. //Process A obtains the offset of the address
  2447. managed_shared_memory::handle handle =
  2448. segment.get_handle_from_address(processA_address);
  2449. //Process A sends this address using any mechanism to process B
  2450. //Process B obtains the handle and transforms it again to an address
  2451. managed_shared_memory::handle handle = ...
  2452. void * processB_address = segment.get_address_from_handle(handle);
  2453. [endsect]
  2454. [section:allocation_types Object construction function family]
  2455. When constructing objects in a managed memory segment (managed shared memory,
  2456. managed mapped files...) associated with a name, the user has a varied object
  2457. construction family to "construct" or to "construct if not found". [*Boost.Interprocess]
  2458. can construct a single object or an array of objects. The array can be constructed with
  2459. the same parameters for all objects or we can define each parameter from a list of iterators:
  2460. [c++]
  2461. //!Allocates and constructs an object of type MyType (throwing version)
  2462. MyType *ptr = managed_memory_segment.construct<MyType>("Name") (par1, par2...);
  2463. //!Allocates and constructs an array of objects of type MyType (throwing version)
  2464. //!Each object receives the same parameters (par1, par2, ...)
  2465. MyType *ptr = managed_memory_segment.construct<MyType>("Name")[count](par1, par2...);
  2466. //!Tries to find a previously created object. If not present, allocates
  2467. //!and constructs an object of type MyType (throwing version)
  2468. MyType *ptr = managed_memory_segment.find_or_construct<MyType>("Name") (par1, par2...);
  2469. //!Tries to find a previously created object. If not present, allocates and
  2470. //!constructs an array of objects of type MyType (throwing version). Each object
  2471. //!receives the same parameters (par1, par2, ...)
  2472. MyType *ptr = managed_memory_segment.find_or_construct<MyType>("Name")[count](par1, par2...);
  2473. //!Allocates and constructs an array of objects of type MyType (throwing version)
  2474. //!Each object receives parameters returned with the expression (*it1++, *it2++,... )
  2475. MyType *ptr = managed_memory_segment.construct_it<MyType>("Name")[count](it1, it2...);
  2476. //!Tries to find a previously created object. If not present, allocates and constructs
  2477. //!an array of objects of type MyType (throwing version). Each object receives
  2478. //!parameters returned with the expression (*it1++, *it2++,... )
  2479. MyType *ptr = managed_memory_segment.find_or_construct_it<MyType>("Name")[count](it1, it2...);
  2480. //!Tries to find a previously created object. Returns a pointer to the object and the
  2481. //!count (if it is not an array, returns 1). If not present, the returned pointer is 0
  2482. std::pair<MyType *,std::size_t> ret = managed_memory_segment.find<MyType>("Name");
  2483. //!Destroys the created object, returns false if not present
  2484. bool destroyed = managed_memory_segment.destroy<MyType>("Name");
  2485. //!Destroys the created object via pointer
  2486. managed_memory_segment.destroy_ptr(ptr);
  2487. All these functions have a non-throwing version, that
  2488. is invoked with an additional parameter std::nothrow.
  2489. For example, for simple object construction:
  2490. [c++]
  2491. //!Allocates and constructs an object of type MyType (no throwing version)
  2492. MyType *ptr = managed_memory_segment.construct<MyType>("Name", std::nothrow) (par1, par2...);
  2493. [endsect]
  2494. [section:anonymous Anonymous instance construction]
  2495. Sometimes, the user doesn't want to create class objects associated with a name.
  2496. For this purpose, [*Boost.Interprocess] can create anonymous objects in a managed
  2497. memory segment. All named object construction functions are available to construct
  2498. anonymous objects. To allocate an anonymous objects, the user must use
  2499. "boost::interprocess::anonymous_instance" name instead of a normal name:
  2500. [c++]
  2501. MyType *ptr = managed_memory_segment.construct<MyType>(anonymous_instance) (par1, par2...);
  2502. //Other construct variants can also be used (including non-throwing ones)
  2503. ...
  2504. //We can only destroy the anonymous object via pointer
  2505. managed_memory_segment.destroy_ptr(ptr);
  2506. Find functions have no sense here, since anonymous objects have no name.
  2507. We can only destroy the anonymous object via pointer.
  2508. [endsect]
  2509. [section:unique Unique instance construction]
  2510. Sometimes, the user wants to emulate a singleton in a managed memory segment. Obviously,
  2511. as the managed memory segment is constructed at run-time, the user must construct and
  2512. destroy this object explicitly. But how can the user be sure that the object is the only
  2513. object of its type in the managed memory segment? This can be emulated using
  2514. a named object and checking if it is present before trying to create one, but
  2515. all processes must agree in the object's name, that can also conflict with
  2516. other existing names.
  2517. To solve this, [*Boost.Interprocess] offers a "unique object" creation in a managed memory segment.
  2518. Only one instance of a class can be created in a managed memory segment using this
  2519. "unique object" service (you can create more named objects of this class, though)
  2520. so it makes easier the emulation of singleton-like objects across processes, for example,
  2521. to design pooled, shared memory allocators. The object can be searched using the type
  2522. of the class as a key.
  2523. [c++]
  2524. // Construct
  2525. MyType *ptr = managed_memory_segment.construct<MyType>(unique_instance) (par1, par2...);
  2526. // Find it
  2527. std::pair<MyType *,std::size_t> ret = managed_memory_segment.find<MyType>(unique_instance);
  2528. // Destroy it
  2529. managed_memory_segment.destroy<MyType>(unique_instance);
  2530. // Other construct and find variants can also be used (including non-throwing ones)
  2531. //...
  2532. [c++]
  2533. // We can also destroy the unique object via pointer
  2534. MyType *ptr = managed_memory_segment.construct<MyType>(unique_instance) (par1, par2...);
  2535. managed_shared_memory.destroy_ptr(ptr);
  2536. The find function obtains a pointer to the only object of type T that can be created
  2537. using this "unique instance" mechanism.
  2538. [endsect]
  2539. [section:synchronization Synchronization guarantees]
  2540. One of the features of named/unique allocations/searches/destructions is that
  2541. they are [*atomic]. Named allocations use the recursive synchronization scheme defined by the
  2542. internal `mutex_family` typedef defined of the memory allocation algorithm template
  2543. parameter (`MemoryAlgorithm`). That is, the mutex type used to synchronize
  2544. named/unique allocations is defined by the
  2545. `MemoryAlgorithm::mutex_family::recursive_mutex_type` type. For shared memory,
  2546. and memory mapped file based managed segments this recursive mutex is defined
  2547. as [classref boost::interprocess::interprocess_recursive_mutex interprocess_recursive_mutex].
  2548. If two processes can call:
  2549. [c++]
  2550. MyType *ptr = managed_shared_memory.find_or_construct<MyType>("Name")[count](par1, par2...);
  2551. at the same time, but only one process will create the object and the other will
  2552. obtain a pointer to the created object.
  2553. Raw allocation using `allocate()` can be called also safely while executing
  2554. named/anonymous/unique allocations, just like when programming a multithreaded
  2555. application inserting an object in a mutex-protected map does not block other threads
  2556. from calling new[] while the map thread is searching the place where it has to insert the
  2557. new object. The synchronization does happen once the map finds the correct place and
  2558. it has to allocate raw memory to construct the new value.
  2559. This means that if we are creating or searching for a lot of named objects,
  2560. we only block creation/searches from other processes but we don't block another
  2561. process if that process is inserting elements in a shared memory vector.
  2562. [endsect]
  2563. [section:index_types Index types for name/object mappings]
  2564. As seen, managed memory segments, when creating named objects, store the name/object
  2565. association in an index. The index is a map with the name of the object as a key and
  2566. a pointer to the object as the mapped type. The default specializations,
  2567. *managed_shared_memory* and *wmanaged_shared_memory*, use *flat_map_index* as the index type.
  2568. Each index has its own characteristics, like search-time, insertion time, deletion time,
  2569. memory use, and memory allocation patterns. [*Boost.Interprocess] offers 3 index types
  2570. right now:
  2571. * [*boost::interprocess::flat_map_index flat_map_index]: Based on boost::interprocess::flat_map, an ordered
  2572. vector similar to Loki library's AssocVector class, offers great search time and
  2573. minimum memory use. But the vector must be reallocated when is full, so all data
  2574. must be copied to the new buffer. Ideal when insertions are mainly in initialization
  2575. time and in run-time we just need searches.
  2576. * [*boost::interprocess::map_index map_index]: Based on boost::interprocess::map, a managed memory ready
  2577. version of std::map. Since it's a node based container, it has no reallocations, the tree
  2578. must be just rebalanced sometimes. Offers equilibrated insertion/deletion/search
  2579. times with more overhead per node comparing to *boost::interprocess::flat_map_index*.
  2580. Ideal when searches/insertions/deletions are in random order.
  2581. * [*boost::interprocess::null_index null_index]: This index is for people using a managed
  2582. memory segment just for raw memory buffer allocations and they don't make use
  2583. of named/unique allocations. This class is just empty and saves some space and
  2584. compilation time.
  2585. If you try to use named object creation with a managed memory segment using this
  2586. index, you will get a compilation error.
  2587. As an example, if we want to define new managed shared memory class
  2588. using *boost::interprocess::map* as the index type we
  2589. just must specify [boost::interprocess::map_index map_index] as a template parameter:
  2590. [c++]
  2591. //This managed memory segment can allocate objects with:
  2592. // -> a wchar_t string as key
  2593. // -> boost::interprocess::rbtree_best_fit with process-shared mutexes
  2594. // as memory allocation algorithm.
  2595. // -> boost::interprocess::map<...> as the index to store name/object mappings
  2596. //
  2597. typedef boost::interprocess::basic_managed_shared_memory
  2598. < wchar_t
  2599. , boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family, offset_ptr<void> >
  2600. , boost::interprocess::map_index
  2601. > my_managed_shared_memory;
  2602. [*Boost.Interprocess] plans to offer an *unordered_map* based index as soon as this
  2603. container is included in Boost. If these indexes are not enough for you, you can define
  2604. your own index type. To know how to do this, go to
  2605. [link interprocess.customizing_interprocess.custom_indexes Building custom indexes] section.
  2606. [endsect]
  2607. [section:managed_memory_segment_segment_manager Segment Manager]
  2608. All [*Boost.Interprocess] managed memory segment classes construct in their
  2609. respective memory segments (shared memory, memory mapped files, heap memory...)
  2610. some structures to implement the memory management algorithm, named allocations,
  2611. synchronization objects... All these objects are encapsulated in a single object
  2612. called [*segment manager]. A managed memory mapped file and a managed shared
  2613. memory use the same [*segment manager] to implement all managed memory segment
  2614. features, due to the fact that a [*segment manager] is a class that manages
  2615. a fixed size memory buffer. Since both shared memory or memory mapped files
  2616. are accessed though a mapped region, and a mapped region is a fixed size
  2617. memory buffer, a single [*segment manager] class can manage several managed
  2618. memory segment types.
  2619. Some [*Boost.Interprocess] classes require a pointer to the segment manager in
  2620. their constructors, and the segment manager can be obtained from any managed
  2621. memory segment using `get_segment_manager` member:
  2622. [c++]
  2623. managed_shared_memory::segment_manager *seg_manager =
  2624. managed_shm.get_segment_manager();
  2625. [endsect]
  2626. [section:managed_memory_segment_information Obtaining information about a constructed object]
  2627. Once an object is constructed using `construct<>` function family, the
  2628. programmer can obtain information about the object using a pointer to the
  2629. object. The programmer can obtain the following information:
  2630. * Name of the object: If it's a named instance, the name used in the construction
  2631. function is returned, otherwise 0 is returned.
  2632. * Length of the object: Returns the number of elements of the object (1 if it's
  2633. a single value, >=1 if it's an array).
  2634. * The type of construction: Whether the object was constructed using a named,
  2635. unique or anonymous construction.
  2636. Here is an example showing this functionality:
  2637. [import ../example/doc_managed_construction_info.cpp]
  2638. [doc_managed_construction_info]
  2639. [endsect]
  2640. [section:managed_memory_segment_atomic_func Executing an object function atomically]
  2641. Sometimes the programmer must execute some code, and needs to execute it with the
  2642. guarantee that no other process or thread will create or destroy any named, unique
  2643. or anonymous object while executing the functor. A user might want to create several
  2644. named objects and initialize them, but those objects should be available for the rest of processes
  2645. at once.
  2646. To achieve this, the programmer can use the `atomic_func()` function offered by
  2647. managed classes:
  2648. [c++]
  2649. //This object function will create several named objects
  2650. create_several_objects_func func(/**/);
  2651. //While executing the function, no other process will be
  2652. //able to create or destroy objects
  2653. managed_memory.atomic_func(func);
  2654. Note that `atomic_func` does not prevent other processes from allocating raw memory
  2655. or executing member functions for already constructed objects (e.g.: another process
  2656. might be pushing elements into a vector placed in the segment). The atomic function
  2657. only blocks named, unique and anonymous creation, search and destruction
  2658. (concurrent calls to `construct<>`, `find<>`, `find_or_construct<>`, `destroy<>`...)
  2659. from other processes.
  2660. [endsect]
  2661. [endsect]
  2662. [section:managed_memory_segment_advanced_features Managed Memory Segment Advanced Features]
  2663. [section:managed_memory_segment_information Obtaining information about the managed segment]
  2664. These functions are available to obtain information about the managed memory segments:
  2665. Obtain the size of the memory segment:
  2666. [c++]
  2667. managed_shm.get_size();
  2668. Obtain the number of free bytes of the segment:
  2669. [c++]
  2670. managed_shm.get_free_memory();
  2671. Clear to zero the free memory:
  2672. [c++]
  2673. managed_shm.zero_free_memory();
  2674. Know if all memory has been deallocated, false otherwise:
  2675. [c++]
  2676. managed_shm.all_memory_deallocated();
  2677. Test internal structures of the managed segment. Returns true
  2678. if no errors are detected:
  2679. [c++]
  2680. managed_shm.check_sanity();
  2681. Obtain the number of named and unique objects allocated in the segment:
  2682. [c++]
  2683. managed_shm.get_num_named_objects();
  2684. managed_shm.get_num_unique_objects();
  2685. [endsect]
  2686. [section:growing_managed_memory Growing managed segments]
  2687. Once a managed segment is created the managed segment can't be grown. The limitation
  2688. is not easily solvable: every process attached to the managed segment would need to
  2689. be stopped, notified of the new size, they would need to remap the managed segment
  2690. and continue working. Nearly impossible to achieve with a user-level library without
  2691. the help of the operating system kernel.
  2692. On the other hand, [*Boost.Interprocess] offers off-line segment growing. What does this
  2693. mean? That the segment can be grown if no process has mapped the managed segment. If the
  2694. application can find a moment where no process is attached it can grow or shrink to fit
  2695. the managed segment.
  2696. Here we have an example showing how to grow and shrink to fit
  2697. [classref boost::interprocess::managed_shared_memory managed_shared_memory]:
  2698. [import ../example/doc_managed_grow.cpp]
  2699. [doc_managed_grow]
  2700. [classref boost::interprocess::managed_mapped_file managed_mapped_file] also
  2701. offers a similar function to grow or shrink_to_fit the managed file.
  2702. Please, remember that [*no process should be modifying the file/shared memory while
  2703. the growing/shrinking process is performed]. Otherwise, the managed segment will be
  2704. corrupted.
  2705. [endsect]
  2706. [section:managed_memory_segment_advanced_index_functions Advanced index functions]
  2707. As mentioned, the managed segment stores the information about named and unique
  2708. objects in two indexes. Depending on the type of those indexes, the index must
  2709. reallocate some auxiliary structures when new named or unique allocations are made.
  2710. For some indexes, if the user knows how many named or unique objects are going to
  2711. be created it's possible to preallocate some structures to obtain much better
  2712. performance. (If the index is an ordered vector it can preallocate memory to avoid
  2713. reallocations. If the index is a hash structure it can preallocate the bucket array).
  2714. The following functions reserve memory to make the subsequent allocation of
  2715. named or unique objects more efficient. These functions are only useful for
  2716. pseudo-intrusive or non-node indexes (like `flat_map_index`,
  2717. `iunordered_set_index`). These functions have no effect with the
  2718. default index (`iset_index`) or other indexes (`map_index`):
  2719. [c++]
  2720. managed_shm.reserve_named_objects(1000);
  2721. managed_shm.reserve_unique_objects(1000);
  2722. [c++]
  2723. managed_shm.reserve_named_objects(1000);
  2724. managed_shm.reserve_unique_objects(1000);
  2725. Managed memory segments also offer the possibility to iterate through
  2726. constructed named and unique objects for debugging purposes. [*Caution: this
  2727. iteration is not thread-safe] so the user should make sure that no other
  2728. thread is manipulating named or unique indexes (creating, erasing,
  2729. reserving...) in the segment. Other operations not involving indexes can
  2730. be concurrently executed (raw memory allocation/deallocations, for example).
  2731. The following functions return constant iterators to the range of named and
  2732. unique objects stored in the managed segment. Depending on the index type,
  2733. iterators might be invalidated after a named or unique
  2734. creation/erasure/reserve operation:
  2735. [c++]
  2736. typedef managed_shared_memory::const_named_iterator const_named_it;
  2737. const_named_it named_beg = managed_shm.named_begin();
  2738. const_named_it named_end = managed_shm.named_end();
  2739. typedef managed_shared_memory::const_unique_iterator const_unique_it;
  2740. const_unique_it unique_beg = managed_shm.unique_begin();
  2741. const_unique_it unique_end = managed_shm.unique_end();
  2742. for(; named_beg != named_end; ++named_beg){
  2743. //A pointer to the name of the named object
  2744. const managed_shared_memory::char_type *name = named_beg->name();
  2745. //The length of the name
  2746. std::size_t name_len = named_beg->name_length();
  2747. //A constant void pointer to the named object
  2748. const void *value = named_beg->value();
  2749. }
  2750. for(; unique_beg != unique_end; ++unique_beg){
  2751. //The typeid(T).name() of the unique object
  2752. const char *typeid_name = unique_beg->name();
  2753. //The length of the name
  2754. std::size_t name_len = unique_beg->name_length();
  2755. //A constant void pointer to the unique object
  2756. const void *value = unique_beg->value();
  2757. }
  2758. [endsect]
  2759. [section:allocate_aligned Allocating aligned memory portions]
  2760. Sometimes it's interesting to be able to allocate aligned fragments of memory
  2761. because of some hardware or software restrictions. Sometimes, having
  2762. aligned memory is a feature that can be used to improve several
  2763. memory algorithms.
  2764. This allocation is similar to the previously shown raw memory allocation but
  2765. it takes an additional parameter specifying the alignment. There is
  2766. a restriction for the alignment: [*the alignment must be power of two].
  2767. If a user wants to allocate many aligned blocks (for example aligned to 128 bytes),
  2768. the size that minimizes the memory waste is a value that's is nearly a multiple
  2769. of that alignment (for example 2*128 - some bytes). The reason for this is that
  2770. every memory allocation usually needs some additional metadata in the first
  2771. bytes of the allocated buffer. If the user can know the value of "some bytes"
  2772. and if the first bytes of a free block of memory are used to fulfill the aligned
  2773. allocation, the rest of the block can be left also aligned and ready for the next
  2774. aligned allocation. Note that requesting [*a size multiple of the alignment is not optimal]
  2775. because lefts the next block of memory unaligned due to the needed metadata.
  2776. Once the programmer knows the size of the payload of every memory allocation,
  2777. he can request a size that will be optimal to allocate aligned chunks
  2778. of memory maximizing both the size of the
  2779. request [*and] the possibilities of future aligned allocations. This information
  2780. is stored in the PayloadPerAllocation constant of managed memory segments.
  2781. Here is a small example showing how aligned allocation is used:
  2782. [import ../example/doc_managed_aligned_allocation.cpp]
  2783. [doc_managed_aligned_allocation]
  2784. [endsect]
  2785. [section:managed_memory_segment_multiple_allocations Multiple allocation functions]
  2786. [caution This feature is experimental, interface and ABI are unstable]
  2787. If an application needs to allocate a lot of memory buffers but it needs
  2788. to deallocate them independently, the application is normally forced to loop
  2789. calling `allocate()`. Managed memory segments offer an alternative function
  2790. to pack several allocations in a single call obtaining memory buffers that:
  2791. * are packed contiguously in memory (which improves locality)
  2792. * can be independently deallocated.
  2793. This allocation method is much faster
  2794. than calling `allocate()` in a loop. The downside is that the segment
  2795. must provide a contiguous memory segment big enough to hold all the allocations.
  2796. Managed memory segments offer this functionality through `allocate_many()` functions.
  2797. There are 2 types of `allocate_many` functions:
  2798. * Allocation of N buffers of memory with the same size.
  2799. * Allocation of N buffers of memory, each one of different size.
  2800. [c++]
  2801. //!Allocates n_elements of elem_bytes bytes.
  2802. //!Throws bad_alloc on failure. chain.size() is not increased on failure.
  2803. void allocate_many(size_type elem_bytes, size_type n_elements, multiallocation_chain &chain);
  2804. //!Allocates n_elements, each one of element_lengths[i]*sizeof_element bytes.
  2805. //!Throws bad_alloc on failure. chain.size() is not increased on failure.
  2806. void allocate_many(const size_type *element_lengths, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain);
  2807. //!Allocates n_elements of elem_bytes bytes.
  2808. //!Non-throwing version. chain.size() is not increased on failure.
  2809. void allocate_many(std::nothrow_t, size_type elem_bytes, size_type n_elements, multiallocation_chain &chain);
  2810. //!Allocates n_elements, each one of
  2811. //!element_lengths[i]*sizeof_element bytes.
  2812. //!Non-throwing version. chain.size() is not increased on failure.
  2813. void allocate_many(std::nothrow_t, const size_type *elem_sizes, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain);
  2814. //!Deallocates all elements contained in chain.
  2815. //!Never throws.
  2816. void deallocate_many(multiallocation_chain &chain);
  2817. Here is a small example showing all this functionality:
  2818. [import ../example/doc_managed_multiple_allocation.cpp]
  2819. [doc_managed_multiple_allocation]
  2820. Allocating N buffers of the same size improves the performance of pools
  2821. and node containers (for example STL-like lists): when inserting a range of
  2822. forward iterators in a STL-like list, the insertion function can detect the
  2823. number of needed elements and allocate in a single call. The nodes still
  2824. can be deallocated.
  2825. Allocating N buffers of different sizes can be used to speed up allocation in
  2826. cases where several objects must always be allocated at the same time but
  2827. deallocated at different times. For example, a class might perform several initial
  2828. allocations (some header data for a network packet, for example) in its
  2829. constructor but also allocations of buffers that might be reallocated in the future
  2830. (the data to be sent through the network). Instead of allocating all the data
  2831. independently, the constructor might use `allocate_many()` to speed up the
  2832. initialization, but it still can deallocate and expand the memory of the variable
  2833. size element.
  2834. In general, `allocate_many` is useful with large values of N. Overuse
  2835. of `allocate_many` can increase the effective memory usage,
  2836. because it can't reuse existing non-contiguous memory fragments that
  2837. might be available for some of the elements.
  2838. [endsect]
  2839. [section:managed_memory_segment_expand_in_place Expand in place memory allocation]
  2840. When programming some data structures such as vectors, memory reallocation becomes
  2841. an important tool to improve performance. Managed memory segments offer an advanced
  2842. reallocation function that offers:
  2843. * Forward expansion: An allocated buffer can be expanded so that the end of the buffer
  2844. is moved further. New data can be written between the old end and the new end.
  2845. * Backwards expansion: An allocated buffer can be expanded so that the beginning of
  2846. the buffer is moved backwards. New data can be written between the new beginning
  2847. and the old beginning.
  2848. * Shrinking: An allocated buffer can be shrunk so that the end of the buffer
  2849. is moved backwards. The memory between the new end and the old end can be reused
  2850. for future allocations.
  2851. The expansion can be combined with the allocation of a new buffer if the expansion
  2852. fails obtaining a function with "expand, if fails allocate a new buffer" semantics.
  2853. Apart from this features, the function always returns the real size of the
  2854. allocated buffer, because many times, due to alignment issues the allocated
  2855. buffer a bit bigger than the requested size. Thus, the programmer can maximize
  2856. the memory use using `allocation_command`.
  2857. Here is the declaration of the function:
  2858. [c++]
  2859. enum boost::interprocess::allocation_type
  2860. {
  2861. //Bitwise OR (|) combinable values
  2862. boost::interprocess::allocate_new = ...,
  2863. boost::interprocess::expand_fwd = ...,
  2864. boost::interprocess::expand_bwd = ...,
  2865. boost::interprocess::shrink_in_place = ...,
  2866. boost::interprocess::nothrow_allocation = ...
  2867. };
  2868. template<class T>
  2869. std::pair<T *, bool>
  2870. allocation_command( boost::interprocess::allocation_type command
  2871. , std::size_t limit_size
  2872. , size_type &prefer_in_recvd_out_size
  2873. , T *&reuse_ptr);
  2874. [*Preconditions for the function]:
  2875. * If the parameter command contains the value `boost::interprocess::shrink_in_place` it can't
  2876. contain any of these values: `boost::interprocess::expand_fwd`, `boost::interprocess::expand_bwd`.
  2877. * If the parameter command contains `boost::interprocess::expand_fwd` or `boost::interprocess::expand_bwd`, the parameter
  2878. `reuse_ptr` must be non-null and returned by a previous allocation function.
  2879. * If the parameter command contains the value `boost::interprocess::shrink_in_place`, the parameter
  2880. `limit_size` must be equal or greater than the parameter `preferred_size`.
  2881. * If the parameter `command` contains any of these values: `boost::interprocess::expand_fwd` or `boost::interprocess::expand_bwd`,
  2882. the parameter `limit_size` must be equal or less than the parameter `preferred_size`.
  2883. [*Which are the effects of this function:]
  2884. * If the parameter command contains the value `boost::interprocess::shrink_in_place`, the function
  2885. will try to reduce the size of the memory block referenced by pointer `reuse_ptr`
  2886. to the value `preferred_size` moving only the end of the block.
  2887. If it's not possible, it will try to reduce the size of the memory block as
  2888. much as possible as long as this results in `size(p) <= limit_size`. Success
  2889. is reported only if this results in `preferred_size <= size(p)` and `size(p) <= limit_size`.
  2890. * If the parameter `command` only contains the value `boost::interprocess::expand_fwd` (with optional
  2891. additional `boost::interprocess::nothrow_allocation`), the allocator will try to increase the size of the
  2892. memory block referenced by pointer reuse moving only the end of the block to the
  2893. value `preferred_size`. If it's not possible, it will try to increase the size
  2894. of the memory block as much as possible as long as this results in
  2895. `size(p) >= limit_size`. Success is reported only if this results in `limit_size <= size(p)`.
  2896. * If the parameter `command` only contains the value `boost::interprocess::expand_bwd` (with optional
  2897. additional `boost::interprocess::nothrow_allocation`), the allocator will try to increase the size of
  2898. the memory block referenced by pointer `reuse_ptr` only moving the start of the
  2899. block to a returned new position `new_ptr`. If it's not possible, it will try to
  2900. move the start of the block as much as possible as long as this results in
  2901. `size(new_ptr) >= limit_size`. Success is reported only if this results in
  2902. `limit_size <= size(new_ptr)`.
  2903. * If the parameter `command` only contains the value `boost::interprocess::allocate_new` (with optional
  2904. additional `boost::interprocess::nothrow_allocation`), the allocator will try to allocate memory for
  2905. `preferred_size` objects. If it's not possible it will try to allocate memory for
  2906. at least `limit_size` objects.
  2907. * If the parameter `command` only contains a combination of `boost::interprocess::expand_fwd` and
  2908. `boost::interprocess::allocate_new`, (with optional additional `boost::interprocess::nothrow_allocation`) the allocator will
  2909. try first the forward expansion. If this fails, it would try a new allocation.
  2910. * If the parameter `command` only contains a combination of `boost::interprocess::expand_bwd` and
  2911. `boost::interprocess::allocate_new` (with optional additional `boost::interprocess::nothrow_allocation`), the allocator will
  2912. try first to obtain `preferred_size` objects using both methods if necessary.
  2913. If this fails, it will try to obtain `limit_size` objects using both methods if
  2914. necessary.
  2915. * If the parameter `command` only contains a combination of `boost::interprocess::expand_fwd` and
  2916. `boost::interprocess::expand_bwd` (with optional additional `boost::interprocess::nothrow_allocation`), the allocator will
  2917. try first forward expansion. If this fails it will try to obtain preferred_size
  2918. objects using backwards expansion or a combination of forward and backwards expansion.
  2919. If this fails, it will try to obtain `limit_size` objects using both methods if
  2920. necessary.
  2921. * If the parameter `command` only contains a combination of allocation_new,
  2922. `boost::interprocess::expand_fwd` and `boost::interprocess::expand_bwd`, (with optional additional `boost::interprocess::nothrow_allocation`)
  2923. the allocator will try first forward expansion. If this fails it will try to obtain
  2924. preferred_size objects using new allocation, backwards expansion or a combination of
  2925. forward and backwards expansion. If this fails, it will try to obtain `limit_size`
  2926. objects using the same methods.
  2927. * The allocator always writes the size or the expanded/allocated/shrunk memory block
  2928. in `received_size`. On failure the allocator writes in `received_size` a possibly
  2929. successful `limit_size` parameter for a new call.
  2930. [*Throws an exception if two conditions are met:]
  2931. * The allocator is unable to allocate/expand/shrink the memory or there is an
  2932. error in preconditions
  2933. * The parameter command does not contain `boost::interprocess::nothrow_allocation`.
  2934. [*This function returns:]
  2935. * The address of the allocated memory or the new address of the expanded memory
  2936. as the first member of the pair. If the parameter command contains
  2937. `boost::interprocess::nothrow_allocation` the first member will be 0
  2938. if the allocation/expansion fails or there is an error in preconditions.
  2939. * The second member of the pair will be false if the memory has been allocated,
  2940. true if the memory has been expanded. If the first member is 0, the second member
  2941. has an undefined value.
  2942. [*Notes:]
  2943. * If the user chooses `char` as template argument the returned buffer will
  2944. be suitably aligned to hold any type.
  2945. * If the user chooses `char` as template argument and a backwards expansion is
  2946. performed, although properly aligned, the returned buffer might not be
  2947. suitable because the distance between the new beginning and the old beginning
  2948. might not multiple of the type the user wants to construct, since due to internal
  2949. restrictions the expansion can be slightly bigger than the requested bytes. [*When
  2950. performing backwards expansion, if you have already constructed objects in the
  2951. old buffer, make sure to specify correctly the type.]
  2952. Here is a small example that shows the use of `allocation_command`:
  2953. [import ../example/doc_managed_allocation_command.cpp]
  2954. [doc_managed_allocation_command]
  2955. `allocation_command` is a very powerful function that can lead to important
  2956. performance gains. It's specially useful when programming vector-like data
  2957. structures where the programmer can minimize both the number of allocation
  2958. requests and the memory waste.
  2959. [endsect]
  2960. [section:copy_on_write_read_only Opening managed shared memory and mapped files with Copy On Write or Read Only modes]
  2961. When mapping a memory segment based on shared memory or files, there is an option to
  2962. open them using [*open_copy_on_write] option. This option is similar to `open_only` but
  2963. every change the programmer does with this managed segment is kept private to this process
  2964. and is not translated to the underlying device (shared memory or file).
  2965. The underlying shared memory or file is opened as read-only so several processes can
  2966. share an initial managed segment and make private changes to it. If many processes
  2967. open a managed segment in copy on write mode and not modified pages from the managed
  2968. segment will be shared between all those processes, with considerable memory savings.
  2969. Opening managed shared memory and mapped files with [*open_read_only] maps the
  2970. underlying device in memory with [*read-only] attributes. This means that any attempt
  2971. to write that memory, either creating objects or locking any mutex might result in an
  2972. page-fault error (and thus, program termination) from the OS. Read-only mode opens
  2973. the underlying device (shared memory, file...) in read-only mode and
  2974. can result in considerable memory savings if several processes just want to process
  2975. a managed memory segment without modifying it. Read-only mode operations are limited:
  2976. * Read-only mode must be used only from managed classes. If the programmer obtains
  2977. the segment manager and tries to use it directly it might result in an access violation.
  2978. The reason for this is that the segment manager is placed in the underlying device
  2979. and does not nothing about the mode it's been mapped in memory.
  2980. * Only const member functions from managed segments should be used.
  2981. * Additionally, the `find<>` member function avoids using internal locks and can be
  2982. used to look for named and unique objects.
  2983. Here is an example that shows the use of these two open modes:
  2984. [import ../example/doc_managed_copy_on_write.cpp]
  2985. [doc_managed_copy_on_write]
  2986. [endsect]
  2987. [endsect]
  2988. [section:managed_heap_memory_external_buffer Managed Heap Memory And Managed External Buffer]
  2989. [*Boost.Interprocess] offers managed shared memory between processes using
  2990. `managed_shared_memory` or `managed_mapped_file`. Two processes just map the same
  2991. the memory mappable resource and read from and write to that object.
  2992. Many times, we don't want to use that shared memory approach and we prefer
  2993. to send serialized data through network, local socket or message queues. Serialization
  2994. can be done through [*Boost.Serialization] or similar library. However, if two processes
  2995. share the same ABI (application binary interface), we could use the same object and
  2996. container construction capabilities of `managed_shared_memory` or `managed_heap_memory`
  2997. to build all the information in a single buffer that will be sent, for example,
  2998. though message queues. The receiver would just copy the data to a local buffer, and it
  2999. could read or modify it directly without deserializing the data . This approach can be
  3000. much more efficient that a complex serialization mechanism.
  3001. Applications for [*Boost.Interprocess] services using non-shared memory buffers:
  3002. * Create and use STL compatible containers and allocators,
  3003. in systems where dynamic memory is not recommendable.
  3004. * Build complex, easily serializable databases in a single buffer:
  3005. * To share data between threads
  3006. * To save and load information from/to files.
  3007. * Duplicate information (containers, allocators, etc...) just copying the contents of
  3008. one buffer to another one.
  3009. * Send complex information and objects/databases using serial/inter-process/network
  3010. communications.
  3011. To help with this management, [*Boost.Interprocess] provides two useful classes,
  3012. `basic_managed_heap_memory` and `basic_managed_external_buffer`:
  3013. [section:managed_external_buffer Managed External Buffer: Constructing all Boost.Interprocess objects in a user provided buffer]
  3014. Sometimes, the user wants to create simple objects, STL compatible containers, STL compatible
  3015. strings and more, all in a single buffer. This buffer could be a big static buffer,
  3016. a memory-mapped auxiliary device or any other user buffer.
  3017. This would allow an easy serialization and we-ll just need to copy the buffer to duplicate
  3018. all the objects created in the original buffer, including complex objects like
  3019. maps, lists.... [*Boost.Interprocess] offers managed memory segment classes to handle user
  3020. provided buffers that allow the same functionality as shared memory classes:
  3021. [c++]
  3022. //Named object creation managed memory segment
  3023. //All objects are constructed in a user provided buffer
  3024. template <
  3025. class CharType,
  3026. class MemoryAlgorithm,
  3027. template<class IndexConfig> class IndexType
  3028. >
  3029. class basic_managed_external_buffer;
  3030. //Named object creation managed memory segment
  3031. //All objects are constructed in a user provided buffer
  3032. // Names are c-strings,
  3033. // Default memory management algorithm
  3034. // (rbtree_best_fit with no mutexes and relative pointers)
  3035. // Name-object mappings are stored in the default index type (flat_map)
  3036. typedef basic_managed_external_buffer <
  3037. char,
  3038. rbtree_best_fit<null_mutex_family, offset_ptr<void> >,
  3039. flat_map_index
  3040. > managed_external_buffer;
  3041. //Named object creation managed memory segment
  3042. //All objects are constructed in a user provided buffer
  3043. // Names are wide-strings,
  3044. // Default memory management algorithm
  3045. // (rbtree_best_fit with no mutexes and relative pointers)
  3046. // Name-object mappings are stored in the default index type (flat_map)
  3047. typedef basic_managed_external_buffer<
  3048. wchar_t,
  3049. rbtree_best_fit<null_mutex_family, offset_ptr<void> >,
  3050. flat_map_index
  3051. > wmanaged_external_buffer;
  3052. To use a managed external buffer, you must include the following header:
  3053. [c++]
  3054. #include <boost/interprocess/managed_external_buffer.hpp>
  3055. Let's see an example of the use of managed_external_buffer:
  3056. [import ../example/doc_managed_external_buffer.cpp]
  3057. [doc_managed_external_buffer]
  3058. [*Boost.Interprocess] STL compatible allocators can also be used to place STL
  3059. compatible containers in the user segment.
  3060. [classref boost::interprocess::basic_managed_external_buffer basic_managed_external_buffer] can
  3061. be also useful to build small databases for embedded systems limiting the size of
  3062. the used memory to a predefined memory chunk, instead of letting the database
  3063. fragment the heap memory.
  3064. [endsect]
  3065. [section:managed_heap_memory Managed Heap Memory: Boost.Interprocess machinery in heap memory]
  3066. The use of heap memory (new/delete) to obtain a buffer where the user wants to store all
  3067. his data is very common, so [*Boost.Interprocess] provides some specialized
  3068. classes that work exclusively with heap memory.
  3069. These are the classes:
  3070. [c++]
  3071. //Named object creation managed memory segment
  3072. //All objects are constructed in a single buffer allocated via new[]
  3073. template <
  3074. class CharType,
  3075. class MemoryAlgorithm,
  3076. template<class IndexConfig> class IndexType
  3077. >
  3078. class basic_managed_heap_memory;
  3079. //Named object creation managed memory segment
  3080. //All objects are constructed in a single buffer allocated via new[]
  3081. // Names are c-strings,
  3082. // Default memory management algorithm
  3083. // (rbtree_best_fit with no mutexes and relative pointers)
  3084. // Name-object mappings are stored in the default index type (flat_map)
  3085. typedef basic_managed_heap_memory <
  3086. char,
  3087. rbtree_best_fit<null_mutex_family>,
  3088. flat_map_index
  3089. > managed_heap_memory;
  3090. //Named object creation managed memory segment
  3091. //All objects are constructed in a single buffer allocated via new[]
  3092. // Names are wide-strings,
  3093. // Default memory management algorithm
  3094. // (rbtree_best_fit with no mutexes and relative pointers)
  3095. // Name-object mappings are stored in the default index type (flat_map)
  3096. typedef basic_managed_heap_memory<
  3097. wchar_t,
  3098. rbtree_best_fit<null_mutex_family>,
  3099. flat_map_index
  3100. > wmanaged_heap_memory;
  3101. To use a managed heap memory, you must include the following header:
  3102. [c++]
  3103. #include <boost/interprocess/managed_heap_memory.hpp>
  3104. The use is exactly the same as
  3105. [classref boost::interprocess::basic_managed_external_buffer basic_managed_external_buffer],
  3106. except that memory is created by
  3107. the managed memory segment itself using dynamic (new/delete) memory.
  3108. [*basic_managed_heap_memory] also offers a `grow(std::size_t extra_bytes)` function that
  3109. tries to resize internal heap memory so that we have room for more objects.
  3110. But *be careful*, if memory is reallocated, the old buffer will be copied into
  3111. the new one so all the objects will be binary-copied to the new buffer.
  3112. To be able to use this function, all pointers constructed in the heap buffer that
  3113. point to objects in the heap buffer must be relative pointers (for example `offset_ptr`).
  3114. Otherwise, the result is undefined. Here is an example:
  3115. [import ../example/doc_managed_heap_memory.cpp]
  3116. [doc_managed_heap_memory]
  3117. [endsect]
  3118. [section:managed_heap_memory_external_buffer_diff Differences between managed memory segments]
  3119. All managed memory segments have similar capabilities
  3120. (memory allocation inside the memory segment, named object construction...),
  3121. but there are some remarkable differences between [*managed_shared_memory],
  3122. [*managed_mapped_file] and [*managed_heap_memory], [*managed_external_file].
  3123. * Default specializations of managed shared memory and mapped file use process-shared
  3124. mutexes. Heap memory and external buffer have no internal synchronization by default.
  3125. The cause is that the first two are thought to be shared between processes (although
  3126. memory mapped files could be used just to obtain a persistent object data-base for a
  3127. process) whereas the last two are thought to be used inside one process to construct
  3128. a serialized named object data-base that can be sent though serial interprocess
  3129. communications (like message queues, localhost network...).
  3130. * The first two create a system-global object (a shared memory object or a file) shared
  3131. by several processes, whereas the last two are objects that don't create system-wide
  3132. resources.
  3133. [endsect]
  3134. [section:shared_message_queue_ex Example: Serializing a database through the message queue]
  3135. To see the utility of managed heap memory and managed external buffer classes,
  3136. the following example shows how a message queue can be used to serialize a whole
  3137. database constructed in a memory buffer using [*Boost.Interprocess], send the database
  3138. through a message queue and duplicated in another buffer:
  3139. [import ../test/message_queue_test.cpp]
  3140. [message_queue_test_test_serialize_db]
  3141. [endsect]
  3142. [endsect]
  3143. [endsect]
  3144. [section:allocators_containers Allocators, containers and memory allocation algorithms]
  3145. [section:allocator_introduction Introduction to Interprocess allocators]
  3146. As seen, [*Boost.Interprocess] offers raw memory allocation and object construction
  3147. using managed memory segments (managed shared memory, managed mapped files...) and
  3148. one of the first user requests is the use of containers in managed shared memories.
  3149. To achieve this, [*Boost.Interprocess] makes use of managed memory segment's
  3150. memory allocation algorithms to build several memory allocation schemes, including
  3151. general purpose and node allocators.
  3152. [*Boost.Interprocess] STL compatible allocators are configurable via template parameters.
  3153. Allocators define their `pointer` typedef based on the `void_pointer` typedef of the segment manager
  3154. passed as template argument. When this `segment_manager::void_pointer` is a relative pointer,
  3155. (for example, `offset_ptr<void>`) the user can place these allocators in
  3156. memory mapped in different base addresses in several processes.
  3157. [section:allocator_properties Properties of [*Boost.Interprocess] allocators]
  3158. Container allocators are normally default-constructible because the are stateless.
  3159. `std::allocator` and [*Boost.Pool's] `boost::pool_allocator`/`boost::fast_pool_allocator`
  3160. are examples of default-constructible allocators.
  3161. On the other hand, [*Boost.Interprocess] allocators need to allocate memory from a
  3162. concrete memory segment and not from a system-wide memory source (like the heap).
  3163. [*Boost.Interprocess] allocators are [*stateful], which means that they must be
  3164. configured to tell them where the shared memory or the memory mapped file is.
  3165. This information is transmitted at compile-time and run-time: The allocators
  3166. receive a template parameter defining the type of the segment manager and
  3167. their constructor receive a pointer to the segment manager of the managed memory
  3168. segment where the user wants to allocate the values.
  3169. [*Boost.Interprocess] allocators have [*no default-constructors] and containers
  3170. must be explicitly initialized with a configured allocator:
  3171. [c++]
  3172. //The allocators must be templatized with the segment manager type
  3173. typedef any_interprocess_allocator
  3174. <int, managed_shared_memory::segment_manager, ...> Allocator;
  3175. //The allocator must be constructed with a pointer to the segment manager
  3176. Allocator alloc_instance (segment.get_segment_manager(), ...);
  3177. //Containers must be initialized with a configured allocator
  3178. typedef my_list<int, Allocator> MyIntList;
  3179. MyIntList mylist(alloc_inst);
  3180. //This would lead to a compilation error, because
  3181. //the allocator has no default constructor
  3182. //MyIntList mylist;
  3183. [*Boost.Interprocess] allocators also have a `get_segment_manager()` function
  3184. that returns the underlying segment manager that they have received in the
  3185. constructor:
  3186. [c++]
  3187. Allocator::segment_manager s = alloc_instance.get_segment_manager();
  3188. AnotherType *a = s->construct<AnotherType>(anonymous_instance)(/*Parameters*/);
  3189. [endsect]
  3190. [section:allocator_swapping Swapping Boost.Interprocess allocators]
  3191. When swapping STL containers, there is an active discussion on what to do with
  3192. the allocators. Some STL implementations, for example Dinkumware from Visual .NET 2003,
  3193. perform a deep swap of the whole container through a temporary when allocators are not equal.
  3194. The [@http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2004/n1599.html proposed resolution]
  3195. to container swapping is that allocators should be swapped in a non-throwing way.
  3196. Unfortunately, this approach is not valid with shared memory. Using heap allocators, if
  3197. Group1 of node allocators share a common segregated storage, and Group2 share another common
  3198. segregated storage, a simple pointer swapping is needed to swap an allocator of Group1 and another
  3199. allocator of Group2. But when the user wants to swap two shared memory allocators, each one
  3200. placed in a different shared memory segment, this is not possible. As generally shared memory
  3201. is mapped in different addresses in each process, a pointer placed in one segment can't point
  3202. to any object placed in other shared memory segment, since in each process, the distance between
  3203. the segments is different. However, if both shared memory allocators are in the same segment,
  3204. a non-throwing swap is possible, just like heap allocators.
  3205. Until a final resolution is achieved. [*Boost.Interprocess] allocators implement a non-throwing
  3206. swap function that swaps internal pointers. If an allocator placed in a shared memory segment is
  3207. swapped with other placed in a different shared memory segment, the result is undefined. But a
  3208. crash is quite sure.
  3209. [endsect]
  3210. [section:allocator allocator: A general purpose allocator for managed memory segments]
  3211. The [classref boost::interprocess::allocator allocator] class defines an allocator class that
  3212. uses the managed memory segment's algorithm to allocate and deallocate memory. This is
  3213. achieved through the [*segment manager] of the managed memory segment. This allocator
  3214. is the equivalent for managed memory segments of the standard `std::allocator`.
  3215. [classref boost::interprocess::allocator allocator]
  3216. is templatized with the allocated type, and the segment manager.
  3217. [*Equality:] Two [classref boost::interprocess::allocator allocator] instances
  3218. constructed with the same segment manager compare equal. If an instance is
  3219. created using copy constructor, that instance compares equal with the original one.
  3220. [*Allocation thread-safety:] Allocation and deallocation are implemented as calls
  3221. to the segment manager's allocation function so the allocator offers the same
  3222. thread-safety as the segment manager.
  3223. To use [classref boost::interprocess::allocator allocator] you must include
  3224. the following header:
  3225. [c++]
  3226. #include <boost/interprocess/allocators/allocator.hpp>
  3227. [classref boost::interprocess::allocator allocator] has the following declaration:
  3228. [c++]
  3229. namespace boost {
  3230. namespace interprocess {
  3231. template<class T, class SegmentManager>
  3232. class allocator;
  3233. } //namespace interprocess {
  3234. } //namespace boost {
  3235. The allocator just provides the needed typedefs and forwards all allocation
  3236. and deallocation requests to the segment manager passed in the constructor, just
  3237. like `std::allocator` forwards the requests to `operator new[]`.
  3238. Using [classref boost::interprocess::allocator allocator] is straightforward:
  3239. [import ../example/doc_allocator.cpp]
  3240. [doc_allocator]
  3241. [endsect]
  3242. [endsect]
  3243. [section:stl_allocators_segregated_storage Segregated storage node allocators]
  3244. Variable size memory algorithms waste
  3245. some space in management information for each allocation. Sometimes,
  3246. usually for small objects, this is not acceptable. Memory algorithms can
  3247. also fragment the managed memory segment under some allocation and
  3248. deallocation schemes, reducing their performance. When allocating
  3249. many objects of the same type, a simple segregated storage becomes
  3250. a fast and space-friendly allocator, as explained in the
  3251. [@http://www.boost.org/libs/pool/ [*Boost.Pool]] library.
  3252. Segregate storage node
  3253. allocators allocate large memory chunks from a general purpose memory
  3254. allocator and divide that chunk into several nodes. No bookkeeping information
  3255. is stored in the nodes to achieve minimal memory waste: free nodes are linked
  3256. using a pointer constructed in the memory of the node.
  3257. [*Boost.Interprocess]
  3258. offers 3 allocators based on this segregated storage algorithm:
  3259. [classref boost::interprocess::node_allocator node_allocator],
  3260. [classref boost::interprocess::private_node_allocator private_node_allocator] and
  3261. [classref boost::interprocess::cached_node_allocator cached_node_allocator].
  3262. To know the details of the implementation of
  3263. of the segregated storage pools see the
  3264. [link interprocess.architecture.allocators_containers.implementation_segregated_storage_pools Implementation of [*Boost.Interprocess] segregated storage pools]
  3265. section.
  3266. [section:segregated_allocators_common Additional parameters and functions of segregated storage node allocators]
  3267. [classref boost::interprocess::node_allocator node_allocator],
  3268. [classref boost::interprocess::private_node_allocator private_node_allocator] and
  3269. [classref boost::interprocess::cached_node_allocator cached_node_allocator] implement
  3270. the standard allocator interface and the functions explained in the
  3271. [link interprocess.allocators_containers.allocator_introduction.allocator_properties Properties of Boost.Interprocess allocators].
  3272. All these allocators are templatized by 3 parameters:
  3273. * `class T`: The type to be allocated.
  3274. * `class SegmentManager`: The type of the segment manager that will be passed in the constructor.
  3275. * `std::size_t NodesPerChunk`: The number of nodes that a memory chunk will contain.
  3276. This value will define the size of the memory the pool will request to the
  3277. segment manager when the pool runs out of nodes. This parameter has a default value.
  3278. These allocators also offer the `deallocate_free_chunks()` function. This function will
  3279. traverse all the memory chunks of the pool and will return to the managed memory segment
  3280. the free chunks of memory. If this function is not used, deallocating the free chunks does
  3281. not happen until the pool is destroyed so the only way to return memory allocated
  3282. by the pool to the segment before destructing the pool is calling manually this function.
  3283. This function is quite time-consuming because it has quadratic complexity (O(N^2)).
  3284. [endsect]
  3285. [section:node_allocator node_allocator: A process-shared segregated storage]
  3286. For heap-memory node allocators (like [*Boost.Pool's] `boost::fast_pool_allocator`
  3287. usually a global, thread-shared singleton
  3288. pool is used for each node size. This is not possible if you try to share
  3289. a node allocator between processes. To achieve this sharing
  3290. [classref boost::interprocess::node_allocator node_allocator]
  3291. uses the segment manager's unique type allocation service
  3292. (see [link interprocess.managed_memory_segments.managed_memory_segment_features.unique Unique instance construction] section).
  3293. In the initialization, a
  3294. [classref boost::interprocess::node_allocator node_allocator]
  3295. object searches this unique object in
  3296. the segment. If it is not preset, it builds one. This way, all
  3297. [classref boost::interprocess::node_allocator node_allocator]
  3298. objects built inside a memory segment share a unique memory pool.
  3299. The common segregated storage is not only shared between node_allocators of the
  3300. same type, but it is also shared between all node allocators that allocate objects
  3301. of the same size, for example, [*node_allocator<uint32>] and [*node_allocator<float32>].
  3302. This saves a lot of memory but also imposes an synchronization overhead for each
  3303. node allocation.
  3304. The dynamically created common segregated storage
  3305. integrates a reference count so that a
  3306. [classref boost::interprocess::node_allocator node_allocator]
  3307. can know if any other
  3308. [classref boost::interprocess::node_allocator node_allocator]
  3309. is attached to the same common segregated storage. When the last
  3310. allocator attached to the pool is destroyed, the pool is destroyed.
  3311. [*Equality:] Two [classref boost::interprocess::node_allocator node_allocator] instances
  3312. constructed with the same segment manager compare equal. If an instance is
  3313. created using copy constructor, that instance compares equal with the original one.
  3314. [*Allocation thread-safety:] Allocation and deallocation are implemented as calls
  3315. to the shared pool. The shared pool offers the same synchronization guarantees
  3316. as the segment manager.
  3317. To use [classref boost::interprocess::node_allocator node_allocator],
  3318. you must include the following header:
  3319. [c++]
  3320. #include <boost/interprocess/allocators/node_allocator.hpp>
  3321. [classref boost::interprocess::node_allocator node_allocator] has the following declaration:
  3322. [c++]
  3323. namespace boost {
  3324. namespace interprocess {
  3325. template<class T, class SegmentManager, std::size_t NodesPerChunk = ...>
  3326. class node_allocator;
  3327. } //namespace interprocess {
  3328. } //namespace boost {
  3329. An example using [classref boost::interprocess::node_allocator node_allocator]:
  3330. [import ../example/doc_node_allocator.cpp]
  3331. [doc_node_allocator]
  3332. [endsect]
  3333. [section:private_node_allocator private_node_allocator: a private segregated storage]
  3334. As said, the node_allocator shares a common segregated storage between
  3335. node_allocators that allocate objects of the same size and this optimizes
  3336. memory usage. However, it needs a unique/named object construction feature
  3337. so that this sharing can be possible. Also
  3338. imposes a synchronization overhead per node allocation because of this share.
  3339. Sometimes, the unique object service is not available (for example, when
  3340. building index types to implement the named allocation service itself) or the
  3341. synchronization overhead is not acceptable. Many times the programmer wants to
  3342. make sure that the pool is destroyed when the allocator is destroyed, to free
  3343. the memory as soon as possible.
  3344. So [*private_node_allocator] uses the same segregated storage as `node_allocator`,
  3345. but each [*private_node_allocator] has its own segregated storage pool. No synchronization
  3346. is used when allocating nodes, so there is far less overhead for an operation
  3347. that usually involves just a few pointer operations when allocating and
  3348. deallocating a node.
  3349. [*Equality:] Two [classref boost::interprocess::private_node_allocator private_node_allocator]
  3350. instances [*never] compare equal. Memory allocated with one allocator [*can't] be
  3351. deallocated with another one.
  3352. [*Allocation thread-safety:] Allocation and deallocation are [*not] thread-safe.
  3353. To use [classref boost::interprocess::private_node_allocator private_node_allocator],
  3354. you must include the following header:
  3355. [c++]
  3356. #include <boost/interprocess/allocators/private_node_allocator.hpp>
  3357. [classref boost::interprocess::private_node_allocator private_node_allocator]
  3358. has the following declaration:
  3359. [c++]
  3360. namespace boost {
  3361. namespace interprocess {
  3362. template<class T, class SegmentManager, std::size_t NodesPerChunk = ...>
  3363. class private_node_allocator;
  3364. } //namespace interprocess {
  3365. } //namespace boost {
  3366. An example using [classref boost::interprocess::private_node_allocator private_node_allocator]:
  3367. [import ../example/doc_private_node_allocator.cpp]
  3368. [doc_private_node_allocator]
  3369. [endsect]
  3370. [section:cached_node_allocator cached_node_allocator: caching nodes to avoid overhead]
  3371. The total node sharing of [classref boost::interprocess::node_allocator node_allocator] can impose a high overhead for some
  3372. applications and the minimal synchronization overhead of [classref boost::interprocess::private_node_allocator private_node_allocator]
  3373. can impose a unacceptable memory waste for other applications.
  3374. To solve this, [*Boost.Interprocess] offers an allocator,
  3375. [classref boost::interprocess::cached_node_allocator cached_node_allocator], that
  3376. allocates nodes from the common pool but caches some of them privately so that following
  3377. allocations have no synchronization overhead. When the cache is full, the allocator
  3378. returns some cached nodes to the common pool, and those will be available to other
  3379. allocators.
  3380. [*Equality:] Two [classref boost::interprocess::cached_node_allocator cached_node_allocator]
  3381. instances constructed with the same segment manager compare equal. If an instance is
  3382. created using copy constructor, that instance compares equal with the original one.
  3383. [*Allocation thread-safety:] Allocation and deallocation are [*not] thread-safe.
  3384. To use [classref boost::interprocess::cached_node_allocator cached_node_allocator],
  3385. you must include the following header:
  3386. [c++]
  3387. #include <boost/interprocess/allocators/cached_node_allocator.hpp>
  3388. [classref boost::interprocess::cached_node_allocator cached_node_allocator]
  3389. has the following declaration:
  3390. [c++]
  3391. namespace boost {
  3392. namespace interprocess {
  3393. template<class T, class SegmentManager, std::size_t NodesPerChunk = ...>
  3394. class cached_node_allocator;
  3395. } //namespace interprocess {
  3396. } //namespace boost {
  3397. A [classref boost::interprocess::cached_node_allocator cached_node_allocator] instance
  3398. and a [classref boost::interprocess::node_allocator node_allocator] instance
  3399. share the same pool if both instances receive the same template parameters. This means
  3400. that nodes returned to the shared pool by one of them can be reused by the other.
  3401. Please note that this does not mean that both allocators compare equal, this is just
  3402. information for programmers that want to maximize the use of the pool.
  3403. [classref boost::interprocess::cached_node_allocator cached_node_allocator], offers
  3404. additional functions to control the cache (the cache can be controlled per instance):
  3405. * `void set_max_cached_nodes(std::size_t n)`: Sets the maximum cached nodes limit.
  3406. If cached nodes reach the limit, some are returned to the shared pool.
  3407. * `std::size_t get_max_cached_nodes() const`: Returns the maximum cached nodes limit.
  3408. * `void deallocate_cache()`: Returns the cached nodes to the shared pool.
  3409. An example using [classref boost::interprocess::cached_node_allocator cached_node_allocator]:
  3410. [import ../example/doc_cached_node_allocator.cpp]
  3411. [doc_cached_node_allocator]
  3412. [endsect]
  3413. [endsect]
  3414. [section:stl_allocators_adaptive Adaptive pool node allocators]
  3415. Node allocators based on simple segregated storage algorithm are both
  3416. space-efficient and fast but they have a problem: they only can grow. Every allocated
  3417. node avoids any payload to store additional data and that leads to the following limitation:
  3418. when a node is deallocated, it's stored in a free list of nodes but memory is not
  3419. returned to the segment manager so a deallocated
  3420. node can be only reused by other containers using the same node pool.
  3421. This behaviour can be problematic if several containers use
  3422. [classref boost::interprocess::node_allocator] to temporarily allocate a lot
  3423. of objects but they end storing a few of them: the node pool will be full of nodes
  3424. that won't be reused wasting memory from the segment.
  3425. Adaptive pool based allocators trade some space (the overhead can be as low as 1%)
  3426. and performance (acceptable for many applications) with the ability to return free chunks
  3427. of nodes to the memory segment, so that they can be used by any other container or managed
  3428. object construction. To know the details of the implementation of
  3429. of "adaptive pools" see the
  3430. [link interprocess.architecture.allocators_containers.implementation_adaptive_pools Implementation of [*Boost.Intrusive] adaptive pools]
  3431. section.
  3432. Like with segregated storage based node allocators, Boost.Interprocess offers
  3433. 3 new allocators: [classref boost::interprocess::adaptive_pool adaptive_pool],
  3434. [classref boost::interprocess::private_adaptive_pool private_adaptive_pool],
  3435. [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool].
  3436. [section:adaptive_allocators_common Additional parameters and functions of adaptive pool node allocators]
  3437. [classref boost::interprocess::adaptive_pool adaptive_pool],
  3438. [classref boost::interprocess::private_adaptive_pool private_adaptive_pool] and
  3439. [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool] implement
  3440. the standard allocator interface and the functions explained in the
  3441. [link interprocess.allocators_containers.allocator_introduction.allocator_properties Properties of Boost.Interprocess allocators].
  3442. All these allocators are templatized by 4 parameters:
  3443. * `class T`: The type to be allocated.
  3444. * `class SegmentManager`: The type of the segment manager that will be passed in the constructor.
  3445. * `std::size_t NodesPerChunk`: The number of nodes that a memory chunk will contain.
  3446. This value will define the size of the memory the pool will request to the
  3447. segment manager when the pool runs out of nodes. This parameter has a default value.
  3448. * `std::size_t MaxFreeChunks`: The maximum number of free chunks that the pool
  3449. will hold. If this limit is reached the pool returns the chunks to the segment manager.
  3450. This parameter has a default value.
  3451. These allocators also offer the `deallocate_free_chunks()` function. This function will
  3452. traverse all the memory chunks of the pool and will return to the managed memory segment
  3453. the free chunks of memory. This function is much faster than for segregated storage
  3454. allocators, because the adaptive pool algorithm offers constant-time access to free
  3455. chunks.
  3456. [endsect]
  3457. [section:adaptive_pool adaptive_pool: a process-shared adaptive pool]
  3458. Just like [classref boost::interprocess::node_allocator node_allocator]
  3459. a global, process-thread pool is used for each node size. In the
  3460. initialization, [classref boost::interprocess::adaptive_pool adaptive_pool]
  3461. searches the pool in the segment. If it is not preset, it builds one.
  3462. The adaptive pool, is created using a unique name.
  3463. The adaptive pool it is also shared between
  3464. all node_allocators that allocate objects of the same size, for example,
  3465. [*adaptive_pool<uint32>] and [*adaptive_pool<float32>].
  3466. The common adaptive pool is destroyed when all the allocators attached
  3467. to the pool are destroyed.
  3468. [*Equality:] Two [classref boost::interprocess::adaptive_pool adaptive_pool] instances
  3469. constructed with the same segment manager compare equal. If an instance is
  3470. created using copy constructor, that instance compares equal with the original one.
  3471. [*Allocation thread-safety:] Allocation and deallocation are implemented as calls
  3472. to the shared pool. The shared pool offers the same synchronization guarantees
  3473. as the segment manager.
  3474. To use [classref boost::interprocess::adaptive_pool adaptive_pool],
  3475. you must include the following header:
  3476. [c++]
  3477. #include <boost/interprocess/allocators/adaptive_pool.hpp>
  3478. [classref boost::interprocess::adaptive_pool adaptive_pool] has the following declaration:
  3479. [c++]
  3480. namespace boost {
  3481. namespace interprocess {
  3482. template<class T, class SegmentManager, std::size_t NodesPerChunk = ..., std::size_t MaxFreeChunks = ...>
  3483. class adaptive_pool;
  3484. } //namespace interprocess {
  3485. } //namespace boost {
  3486. An example using [classref boost::interprocess::adaptive_pool adaptive_pool]:
  3487. [import ../example/doc_adaptive_pool.cpp]
  3488. [doc_adaptive_pool]
  3489. [endsect]
  3490. [section:private_adaptive_pool private_adaptive_pool: a private adaptive pool]
  3491. Just like [classref boost::interprocess::private_node_allocator private_node_allocator]
  3492. owns a private segregated storage pool,
  3493. [classref boost::interprocess::private_adaptive_pool private_adaptive_pool] owns
  3494. its own adaptive pool. If the user wants to avoid the excessive node allocation
  3495. synchronization overhead in a container
  3496. [classref boost::interprocess::private_adaptive_pool private_adaptive_pool]
  3497. is a good choice.
  3498. [*Equality:] Two [classref boost::interprocess::private_adaptive_pool private_adaptive_pool]
  3499. instances [*never] compare equal. Memory allocated with one allocator [*can't] be
  3500. deallocated with another one.
  3501. [*Allocation thread-safety:] Allocation and deallocation are [*not] thread-safe.
  3502. To use [classref boost::interprocess::private_adaptive_pool private_adaptive_pool],
  3503. you must include the following header:
  3504. [c++]
  3505. #include <boost/interprocess/allocators/private_adaptive_pool.hpp>
  3506. [classref boost::interprocess::private_adaptive_pool private_adaptive_pool]
  3507. has the following declaration:
  3508. [c++]
  3509. namespace boost {
  3510. namespace interprocess {
  3511. template<class T, class SegmentManager, std::size_t NodesPerChunk = ..., std::size_t MaxFreeChunks = ...>
  3512. class private_adaptive_pool;
  3513. } //namespace interprocess {
  3514. } //namespace boost {
  3515. An example using [classref boost::interprocess::private_adaptive_pool private_adaptive_pool]:
  3516. [import ../example/doc_private_adaptive_pool.cpp]
  3517. [doc_private_adaptive_pool]
  3518. [endsect]
  3519. [section:cached_adaptive_pool cached_adaptive_pool: Avoiding synchronization overhead]
  3520. Adaptive pools have also a cached version. In this allocator the allocator caches
  3521. some nodes to avoid the synchronization and bookkeeping overhead of the shared
  3522. adaptive pool.
  3523. [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool]
  3524. allocates nodes from the common adaptive pool but caches some of them privately so that following
  3525. allocations have no synchronization overhead. When the cache is full, the allocator
  3526. returns some cached nodes to the common pool, and those will be available to other
  3527. [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pools] or
  3528. [classref boost::interprocess::adaptive_pool adaptive_pools] of the same managed segment.
  3529. [*Equality:] Two [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool]
  3530. instances constructed with the same segment manager compare equal. If an instance is
  3531. created using copy constructor, that instance compares equal with the original one.
  3532. [*Allocation thread-safety:] Allocation and deallocation are [*not] thread-safe.
  3533. To use [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool],
  3534. you must include the following header:
  3535. [c++]
  3536. #include <boost/interprocess/allocators/cached_adaptive_pool.hpp>
  3537. [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool]
  3538. has the following declaration:
  3539. [c++]
  3540. namespace boost {
  3541. namespace interprocess {
  3542. template<class T, class SegmentManager, std::size_t NodesPerChunk = ..., std::size_t MaxFreeNodes = ...>
  3543. class cached_adaptive_pool;
  3544. } //namespace interprocess {
  3545. } //namespace boost {
  3546. A [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool] instance
  3547. and an [classref boost::interprocess::adaptive_pool adaptive_pool] instance
  3548. share the same pool if both instances receive the same template parameters. This means
  3549. that nodes returned to the shared pool by one of them can be reused by the other.
  3550. Please note that this does not mean that both allocators compare equal, this is just
  3551. information for programmers that want to maximize the use of the pool.
  3552. [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool], offers
  3553. additional functions to control the cache (the cache can be controlled per instance):
  3554. * `void set_max_cached_nodes(std::size_t n)`: Sets the maximum cached nodes limit.
  3555. If cached nodes reach the limit, some are returned to the shared pool.
  3556. * `std::size_t get_max_cached_nodes() const`: Returns the maximum cached nodes limit.
  3557. * `void deallocate_cache()`: Returns the cached nodes to the shared pool.
  3558. An example using [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool]:
  3559. [import ../example/doc_cached_adaptive_pool.cpp]
  3560. [doc_cached_adaptive_pool]
  3561. [endsect]
  3562. [endsect]
  3563. [section:containers_explained Interprocess and containers in managed memory segments]
  3564. [section:stl_container_requirements Container requirements for Boost.Interprocess allocators]
  3565. [*Boost.Interprocess] STL compatible allocators offer a STL compatible allocator
  3566. interface and if they define their internal *pointer* typedef as a relative pointer,
  3567. they can be used to place STL containers in shared memory, memory mapped files or
  3568. in a user defined memory segment.
  3569. However, as Scott Meyers mentions in his Effective STL
  3570. book, Item 10, ['"Be aware of allocator conventions and
  3571. restrictions"]:
  3572. * ['"the Standard explicitly allows library implementers
  3573. to assume that every allocator's pointer typedef is
  3574. a synonym for T*"]
  3575. * ['"the Standard says that an implementation of the STL is
  3576. permitted to assume that all allocator objects of the
  3577. same type are equivalent and always compare equal"]
  3578. Obviously, if any STL implementation ignores pointer typedefs,
  3579. no smart pointer can be used as allocator::pointer. If STL
  3580. implementations assume all allocator objects of the same
  3581. type compare equal, it will assume that two allocators,
  3582. each one allocating from a different memory pool
  3583. are equal, which is a complete disaster.
  3584. STL containers that we want to place in shared memory or memory
  3585. mapped files with [*Boost.Interprocess] can't make any of these assumptions, so:
  3586. * STL containers may not assume that memory allocated with
  3587. an allocator can be deallocated with other allocators of
  3588. the same type. All allocators objects must compare equal
  3589. only if memory allocated with one object can be deallocated
  3590. with the other one, and this can only tested with
  3591. operator==() at run-time.
  3592. * Containers' internal pointers should be of the type allocator::pointer
  3593. and containers may not assume allocator::pointer is a raw pointer.
  3594. * All objects must be constructed-destroyed via
  3595. allocator::construct and allocator::destroy functions.
  3596. [endsect]
  3597. [section:containers STL containers in managed memory segments]
  3598. Unfortunately, many STL implementations use raw pointers
  3599. for internal data and ignore allocator pointer typedefs
  3600. and others suppose at some point that the allocator::typedef
  3601. is T*. This is because in practice,
  3602. there wasn't need of allocators with a pointer typedef
  3603. different from T* for pooled/node memory
  3604. allocators.
  3605. Until STL implementations handle allocator::pointer typedefs
  3606. in a generic way, [*Boost.Interprocess] offers the following classes:
  3607. * [*boost:interprocess::vector] is the implementation of `std::vector` ready
  3608. to be used in managed memory segments like shared memory. To use it include:
  3609. [c++]
  3610. #include <boost/interprocess/containers/vector.hpp>
  3611. * [*boost:interprocess::deque] is the implementation of `std::deque` ready
  3612. to be used in managed memory segments like shared memory. To use it include:
  3613. [c++]
  3614. #include <boost/interprocess/containers/deque.hpp>
  3615. * [classref boost::interprocess::list list] is the implementation of `std::list` ready
  3616. to be used in managed memory segments like shared memory. To use it include:
  3617. [c++]
  3618. #include <boost/interprocess/containers/list.hpp>
  3619. * [classref boost::interprocess::slist slist] is the implementation of SGI's `slist` container (singly linked list) ready
  3620. to be used in managed memory segments like shared memory. To use it include:
  3621. [c++]
  3622. #include <boost/interprocess/containers/slist.hpp>
  3623. * [classref boost::interprocess::set set]/
  3624. [classref boost::interprocess::multiset multiset]/
  3625. [classref boost::interprocess::map map]/
  3626. [classref boost::interprocess::multimap multimap] family is the implementation of
  3627. std::set/multiset/map/multimap family ready
  3628. to be used in managed memory segments like shared memory. To use them include:
  3629. [c++]
  3630. #include <boost/interprocess/containers/set.hpp>
  3631. #include <boost/interprocess/containers/map.hpp>
  3632. * [classref boost::interprocess::flat_set flat_set]/
  3633. [classref boost::interprocess::flat_multiset flat_multiset]/
  3634. [classref boost::interprocess::flat_map flat_map]/
  3635. [classref boost::interprocess::flat_multimap flat_multimap] classes are the
  3636. adaptation and extension of Andrei Alexandrescu's famous AssocVector class
  3637. from Loki library, ready for the shared memory. These classes offer the same
  3638. functionality as `std::set/multiset/map/multimap` implemented with an ordered vector,
  3639. which has faster lookups than the standard ordered associative containers
  3640. based on red-black trees, but slower insertions. To use it include:
  3641. [c++]
  3642. #include <boost/interprocess/containers/flat_set.hpp>
  3643. #include <boost/interprocess/containers/flat_map.hpp>
  3644. * [classref boost::interprocess::basic_string basic_string]
  3645. is the implementation of `std::basic_string` ready
  3646. to be used in managed memory segments like shared memory.
  3647. It's implemented using a vector-like contiguous storage, so
  3648. it has fast c string conversion and can be used with the
  3649. [link interprocess.streams.vectorstream vectorstream] iostream formatting classes.
  3650. To use it include:
  3651. [c++]
  3652. #include <boost/interprocess/containers/string.hpp>
  3653. All these containers have the same default arguments as standard
  3654. containers and they can be used with other, non [*Boost.Interprocess]
  3655. allocators (std::allocator, or boost::pool_allocator, for example).
  3656. To place any of these containers in managed memory segments, we must
  3657. define the allocator template parameter with a [*Boost.Interprocess] allocator
  3658. so that the container allocates the values in the managed memory segment.
  3659. To place the container itself in shared memory, we construct it
  3660. in the managed memory segment just like any other object with [*Boost.Interprocess]:
  3661. [import ../example/doc_cont.cpp]
  3662. [doc_cont]
  3663. These containers also show how easy is to create/modify
  3664. an existing container making possible to place it in shared memory.
  3665. [endsect]
  3666. [section:where_allocate Where is this being allocated?]
  3667. [*Boost.Interprocess] containers are placed in shared memory/memory mapped files,
  3668. etc... using two mechanisms [*at the same time]:
  3669. * [*Boost.Interprocess ]`construct<>`, `find_or_construct<>`... functions. These
  3670. functions place a C++ object in the shared memory/memory mapped file. But this
  3671. places only the object, but *not* the memory that this object may allocate dynamically.
  3672. * Shared memory allocators. These allow allocating shared memory/memory mapped file
  3673. portions so that containers can allocate dynamically fragments of memory to store
  3674. newly inserted elements.
  3675. This means that to place any [*Boost.Interprocess] container (including
  3676. [*Boost.Interprocess] strings) in shared memory or memory mapped files,
  3677. containers *must*:
  3678. * Define their template allocator parameter to a [*Boost.Interprocess] allocator.
  3679. * Every container constructor must take the [*Boost.Interprocess] allocator as parameter.
  3680. * You must use construct<>/find_or_construct<>... functions to place the container
  3681. in the managed memory.
  3682. If you do the first two points but you don't use `construct<>` or `find_or_construct<>`
  3683. you are creating a container placed *only* in your process but that allocates memory
  3684. for contained types from shared memory/memory mapped file.
  3685. Let's see an example:
  3686. [import ../example/doc_where_allocate.cpp]
  3687. [doc_where_allocate]
  3688. [endsect]
  3689. [section:containers_and_move Move semantics in Interprocess containers]
  3690. [*Boost.Interprocess] containers support move semantics, which means that the contents
  3691. of a container can be moved from a container to another one, without any copying. The
  3692. contents of the source container are transferred to the target container and the source
  3693. container is left in default-constructed state.
  3694. When using containers of containers, we can also use move-semantics to insert
  3695. objects in the container, avoiding unnecessary copies.
  3696. To transfer the contents of a container to another one, use
  3697. `boost::move()` function, as shown in the example. For more details
  3698. about functions supporting move-semantics, see the reference section of
  3699. Boost.Interprocess containers:
  3700. [import ../example/doc_move_containers.cpp]
  3701. [doc_move_containers]
  3702. [endsect]
  3703. [section:containers_of_containers Containers of containers]
  3704. When creating containers of containers, each container needs an allocator.
  3705. To avoid using several allocators with complex type definitions, we can take
  3706. advantage of the type erasure provided by void allocators and the ability
  3707. to implicitly convert void allocators in allocators that allocate other types.
  3708. Here we have an example that builds a map in shared memory. Key is a string
  3709. and the mapped type is a class that stores several containers:
  3710. [import ../example/doc_complex_map.cpp]
  3711. [doc_complex_map]
  3712. [endsect]
  3713. [endsect]
  3714. [section:additional_containers Boost containers compatible with Boost.Interprocess]
  3715. As mentioned, container developers might need to change their implementation to make them
  3716. compatible with Boost.Interprocess, because implementation usually ignore allocators with
  3717. smart pointers. Hopefully several Boost containers are compatible with [*Interprocess].
  3718. [section:unordered Boost unordered containers]
  3719. [*Boost.Unordered] containers are compatible with Interprocess, so programmers can store
  3720. hash containers in shared memory and memory mapped files. Here is a small example storing
  3721. `unordered_map` in shared memory:
  3722. [import ../example/doc_unordered_map.cpp]
  3723. [doc_unordered_map]
  3724. [endsect]
  3725. [section:multi_index Boost.MultiIndex containers]
  3726. The widely used [*Boost.MultiIndex] library is compatible with [*Boost.Interprocess] so
  3727. we can construct pretty good databases in shared memory. Constructing databases in shared
  3728. memory is a bit tougher than in normal memory, usually because those databases contain strings
  3729. and those strings need to be placed in shared memory. Shared memory strings require
  3730. an allocator in their constructors so this usually makes object insertion a bit more
  3731. complicated.
  3732. Here is an example that shows how to put a multi index container in shared memory:
  3733. [import ../example/doc_multi_index.cpp]
  3734. [doc_multi_index]
  3735. [endsect]
  3736. Programmers can place [*Boost.CircularBuffer] containers in sharecd memory provided
  3737. they disable debugging facilities with defines `BOOST_CB_DISABLE_DEBUG` or the more
  3738. general `NDEBUG`. The reason is that those debugging facilities are only compatible
  3739. with raw pointers.
  3740. [endsect]
  3741. [endsect]
  3742. [section:memory_algorithms Memory allocation algorithms]
  3743. [section:simple_seq_fit simple_seq_fit: A simple shared memory management algorithm]
  3744. The algorithm is a variation of sequential fit using singly
  3745. linked list of free memory buffers. The algorithm is based
  3746. on the article about shared memory titled
  3747. [@http://home.earthlink.net/~joshwalker1/writing/SharedMemory.html ['"Taming Shared Memory"] ].
  3748. The algorithm is as follows:
  3749. The shared memory is divided in blocks of free shared memory,
  3750. each one with some control data and several bytes of memory
  3751. ready to be used. The control data contains a pointer (in
  3752. our case offset_ptr) to the next free block and the size of
  3753. the block. The allocator consists of a singly linked list
  3754. of free blocks, ordered by address. The last block, points
  3755. always to the first block:
  3756. [c++]
  3757. simple_seq_fit memory layout:
  3758. main extra allocated free_block_1 allocated free_block_2 allocated free_block_3
  3759. header header block ctrl usr block ctrl usr block ctrl usr
  3760. _________ _____ _________ _______________ _________ _______________ _________ _______________
  3761. | || || || | || || | || || | |
  3762. |free|ctrl||extra|| ||next|size| mem || ||next|size| mem || ||next|size| mem |
  3763. |_________||_____||_________||_________|_____||_________||_________|_____||_________||_________|_____|
  3764. | | | | | | |
  3765. |_>_>_>_>_>_>_>_>_>_>_>_>_| |_>_>_>_>_>_>_>_>_>_>_>_>_| |_>_>_>_>_>_>_>_>_>_>_>_| |
  3766. | |
  3767. |_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<__|
  3768. When a user requests N bytes of memory, the allocator
  3769. traverses the free block list looking for a block large
  3770. enough. If the "mem" part of the block has the same
  3771. size as the requested memory, we erase the block from
  3772. the list and return a pointer to the "mem" part of the
  3773. block. If the "mem" part size is bigger than needed,
  3774. we split the block in two blocks, one of the requested
  3775. size and the other with remaining size. Now, we take
  3776. the block with the exact size, erase it from list and
  3777. give it to the user.
  3778. When the user deallocates a block, we traverse the list (remember
  3779. that the list is ordered), and search its place depending on
  3780. the block address. Once found, we try to merge the block with
  3781. adjacent blocks if possible.
  3782. To ease implementation, the size of the free memory block
  3783. is measured in multiples of "basic_size" bytes. The basic
  3784. size will be the size of the control block aligned to
  3785. machine most restrictive alignment.
  3786. This algorithm is a low size overhead algorithm suitable for simple allocation
  3787. schemes. This algorithm should only be used when size is a major concern, because
  3788. the performance of this algorithm suffers when the memory is fragmented. This
  3789. algorithm has linear allocation and deallocation time, so when the number
  3790. of allocations is high, the user should use a more performance-friendly algorithm.
  3791. In most 32 systems, with 8 byte alignment, "basic_size" is 8 bytes.
  3792. This means that an allocation request of 1 byte leads to
  3793. the creation of a 16 byte block, where 8 bytes are available to the user.
  3794. The allocation of 8 bytes leads also to the same 16 byte block.
  3795. [endsect]
  3796. [section:rbtree_best_fit rbtree_best_fit: Best-fit logarithmic-time complexity allocation]
  3797. This algorithm is an advanced algorithm using red-black trees to sort the free
  3798. portions of the memory segment by size. This allows logarithmic complexity
  3799. allocation. Apart from this, a doubly-linked list of all portions of memory
  3800. (free and allocated) is maintained to allow constant-time access to previous
  3801. and next blocks when doing merging operations.
  3802. The data used to create the red-black tree of free nodes is overwritten by the user
  3803. since it's no longer used once the memory is allocated. This maintains the memory
  3804. size overhead down to the doubly linked list overhead, which is pretty small (two pointers).
  3805. Basically this is the scheme:
  3806. [c++]
  3807. rbtree_best_fit memory layout:
  3808. main allocated block free block allocated block free block
  3809. header
  3810. _______________ _______________ _________________________________ _______________ _________________________________
  3811. | || | || | | || | || | | |
  3812. | main header ||next|prev| mem ||next|prev|left|right|parent| mem ||next|prev| mem ||next|prev|left|right|parent| mem |
  3813. |_______________||_________|_____||_________|_________________|_____||_________|_____||_________|_________________|_____|
  3814. This allocation algorithm is pretty fast and scales well with big shared memory
  3815. segments and big number of allocations. To form a block a minimum memory size is needed:
  3816. the sum of the doubly linked list and the red-black tree control data.
  3817. The size of a block is measured in multiples of the most restrictive alignment value.
  3818. In most 32 systems with 8 byte alignment the minimum size of a block is 24 byte.
  3819. When a block is allocated the control data related to the red black tree
  3820. is overwritten by the user (because it's only needed for free blocks).
  3821. In those systems a 1 byte allocation request means that:
  3822. * 24 bytes of memory from the segment are used to form a block.
  3823. * 16 bytes of them are usable for the user.
  3824. For really small allocations (<= 8 bytes), this algorithm wastes more memory than the
  3825. simple sequential fit algorithm (8 bytes more).
  3826. For allocations bigger than 8 bytes the memory overhead is exactly the same.
  3827. This is the default allocation algorithm in [*Boost.Interprocess] managed memory
  3828. segments.
  3829. [endsect]
  3830. [endsect]
  3831. [section:streams Direct iostream formatting: vectorstream and bufferstream]
  3832. Shared memory, memory-mapped files and all [*Boost.Interprocess] mechanisms are focused
  3833. on efficiency. The reason why shared memory is used is that it's the
  3834. fastest IPC mechanism available. When passing text-oriented messages through
  3835. shared memory, there is need to format the message. Obviously C++ offers
  3836. the iostream framework for that work.
  3837. Some programmers appreciate the iostream safety and design for memory
  3838. formatting but feel that the stringstream family is far from efficient not
  3839. when formatting, but when obtaining formatted data to a string, or when
  3840. setting the string from which the stream will extract data. An example:
  3841. [c++]
  3842. //Some formatting elements
  3843. std::string my_text = "...";
  3844. int number;
  3845. //Data reader
  3846. std::istringstream input_processor;
  3847. //This makes a copy of the string. If not using a
  3848. //reference counted string, this is a serious overhead.
  3849. input_processor.str(my_text);
  3850. //Extract data
  3851. while(/*...*/){
  3852. input_processor >> number;
  3853. }
  3854. //Data writer
  3855. std::ostringstream output_processor;
  3856. //Write data
  3857. while(/*...*/){
  3858. output_processor << number;
  3859. }
  3860. //This returns a temporary string. Even with return-value
  3861. //optimization this is expensive.
  3862. my_text = input_processor.str();
  3863. The problem is even worse if the string is a shared-memory string, because
  3864. to extract data, we must copy the data first from shared-memory to a
  3865. `std::string` and then to a `std::stringstream`. To encode data in a shared memory
  3866. string we should copy data from a `std::stringstream` to a `std::string` and then
  3867. to the shared-memory string.
  3868. Because of this overhead, [*Boost.Interprocess] offers a way to format memory-strings
  3869. (in shared memory, memory mapped files or any other memory segment) that
  3870. can avoid all unneeded string copy and memory allocation/deallocations, while
  3871. using all iostream facilities. [*Boost.Interprocess] *vectorstream* and *bufferstream* implement
  3872. vector-based and fixed-size buffer based storage support for iostreams and
  3873. all the formatting/locale hard work is done by standard `std::basic_streambuf<>`
  3874. and `std::basic_iostream<>` classes.
  3875. [section:vectorstream Formatting directly in your character vector: vectorstream]
  3876. The *vectorstream* class family (*basic_vectorbuf*, *basic_ivectorstream*
  3877. ,*basic_ovectorstream* and *basic_vectorstream*) is an efficient way to obtain
  3878. formatted reading/writing directly in a character vector. This way, if
  3879. a shared-memory vector is used, data is extracted/written from/to the shared-memory
  3880. vector, without additional copy/allocation. We can see the declaration of
  3881. basic_vectorstream here:
  3882. //!A basic_iostream class that holds a character vector specified by CharVector
  3883. //!template parameter as its formatting buffer. The vector must have
  3884. //!contiguous storage, like std::vector, boost::interprocess::vector or
  3885. //!boost::interprocess::basic_string
  3886. template <class CharVector, class CharTraits =
  3887. std::char_traits<typename CharVector::value_type> >
  3888. class basic_vectorstream
  3889. : public std::basic_iostream<typename CharVector::value_type, CharTraits>
  3890. {
  3891. public:
  3892. typedef CharVector vector_type;
  3893. typedef typename std::basic_ios
  3894. <typename CharVector::value_type, CharTraits>::char_type char_type;
  3895. typedef typename std::basic_ios<char_type, CharTraits>::int_type int_type;
  3896. typedef typename std::basic_ios<char_type, CharTraits>::pos_type pos_type;
  3897. typedef typename std::basic_ios<char_type, CharTraits>::off_type off_type;
  3898. typedef typename std::basic_ios<char_type, CharTraits>::traits_type traits_type;
  3899. //!Constructor. Throws if vector_type default constructor throws.
  3900. basic_vectorstream(std::ios_base::openmode mode
  3901. = std::ios_base::in | std::ios_base::out);
  3902. //!Constructor. Throws if vector_type(const Parameter &param) throws.
  3903. template<class Parameter>
  3904. basic_vectorstream(const Parameter &param, std::ios_base::openmode mode
  3905. = std::ios_base::in | std::ios_base::out);
  3906. ~basic_vectorstream(){}
  3907. //!Returns the address of the stored stream buffer.
  3908. basic_vectorbuf<CharVector, CharTraits>* rdbuf() const;
  3909. //!Swaps the underlying vector with the passed vector.
  3910. //!This function resets the position in the stream.
  3911. //!Does not throw.
  3912. void swap_vector(vector_type &vect);
  3913. //!Returns a const reference to the internal vector.
  3914. //!Does not throw.
  3915. const vector_type &vector() const;
  3916. //!Preallocates memory from the internal vector.
  3917. //!Resets the stream to the first position.
  3918. //!Throws if the internals vector's memory allocation throws.
  3919. void reserve(typename vector_type::size_type size);
  3920. };
  3921. The vector type is templatized, so that we can use any type of vector:
  3922. [*std::vector], [classref boost::interprocess::vector]... But the storage must be *contiguous*,
  3923. we can't use a deque. We can even use *boost::interprocess::basic_string*, since it has a
  3924. vector interface and it has contiguous storage. *We can't use std::string*, because
  3925. although some std::string implementation are vector-based, others can have
  3926. optimizations and reference-counted implementations.
  3927. The user can obtain a const reference to the internal vector using
  3928. `vector_type vector() const` function and he also can swap the internal vector
  3929. with an external one calling `void swap_vector(vector_type &vect)`.
  3930. The swap function resets the stream position.
  3931. This functions allow efficient methods to obtain the formatted data avoiding
  3932. all allocations and data copies.
  3933. Let's see an example to see how to use vectorstream:
  3934. [import ../example/doc_vectorstream.cpp]
  3935. [doc_vectorstream]
  3936. [endsect]
  3937. [section:bufferstream Formatting directly in your character buffer: bufferstream]
  3938. As seen, vectorstream offers an easy and secure way for efficient iostream
  3939. formatting, but many times, we have to read or write formatted data from/to a
  3940. fixed size character buffer (a static buffer, a c-string, or any other).
  3941. Because of the overhead of stringstream, many developers (specially in
  3942. embedded systems) choose sprintf family. The *bufferstream* classes offer
  3943. iostream interface with direct formatting in a fixed size memory buffer with
  3944. protection against buffer overflows. This is the interface:
  3945. //!A basic_iostream class that uses a fixed size character buffer
  3946. //!as its formatting buffer.
  3947. template <class CharT, class CharTraits = std::char_traits<CharT> >
  3948. class basic_bufferstream
  3949. : public std::basic_iostream<CharT, CharTraits>
  3950. {
  3951. public: // Typedefs
  3952. typedef typename std::basic_ios
  3953. <CharT, CharTraits>::char_type char_type;
  3954. typedef typename std::basic_ios<char_type, CharTraits>::int_type int_type;
  3955. typedef typename std::basic_ios<char_type, CharTraits>::pos_type pos_type;
  3956. typedef typename std::basic_ios<char_type, CharTraits>::off_type off_type;
  3957. typedef typename std::basic_ios<char_type, CharTraits>::traits_type traits_type;
  3958. //!Constructor. Does not throw.
  3959. basic_bufferstream(std::ios_base::openmode mode
  3960. = std::ios_base::in | std::ios_base::out);
  3961. //!Constructor. Assigns formatting buffer. Does not throw.
  3962. basic_bufferstream(CharT *buffer, std::size_t length,
  3963. std::ios_base::openmode mode
  3964. = std::ios_base::in | std::ios_base::out);
  3965. //!Returns the address of the stored stream buffer.
  3966. basic_bufferbuf<CharT, CharTraits>* rdbuf() const;
  3967. //!Returns the pointer and size of the internal buffer.
  3968. //!Does not throw.
  3969. std::pair<CharT *, std::size_t> buffer() const;
  3970. //!Sets the underlying buffer to a new value. Resets
  3971. //!stream position. Does not throw.
  3972. void buffer(CharT *buffer, std::size_t length);
  3973. };
  3974. //Some typedefs to simplify usage
  3975. typedef basic_bufferstream<char> bufferstream;
  3976. typedef basic_bufferstream<wchar_t> wbufferstream;
  3977. // ...
  3978. While reading from a fixed size buffer, *bufferstream* activates endbit flag if
  3979. we try to read an address beyond the end of the buffer. While writing to a
  3980. fixed size buffer, *bufferstream* will active the badbit flag if a buffer overflow
  3981. is going to happen and disallows writing. This way, the fixed size buffer
  3982. formatting through *bufferstream* is secure and efficient, and offers a good
  3983. alternative to sprintf/sscanf functions. Let's see an example:
  3984. [import ../example/doc_bufferstream.cpp]
  3985. [doc_bufferstream]
  3986. As seen, *bufferstream* offers an efficient way to format data without any
  3987. allocation and extra copies. This is very helpful in embedded systems, or
  3988. formatting inside time-critical loops, where stringstream extra copies would
  3989. be too expensive. Unlike sprintf/sscanf, it has protection against buffer
  3990. overflows. As we know, according to the *Technical Report on C++ Performance*,
  3991. it's possible to design efficient iostreams for embedded platforms, so this
  3992. bufferstream class comes handy to format data to stack, static or shared memory
  3993. buffers.
  3994. [endsect]
  3995. [endsect]
  3996. [section:interprocess_smart_ptr Ownership smart pointers]
  3997. C++ users know the importance of ownership smart pointers when dealing with resources.
  3998. Boost offers a wide range of such type of pointers: `intrusive_ptr<>`,
  3999. `scoped_ptr<>`, `shared_ptr<>`...
  4000. When building complex shared memory/memory mapped files structures, programmers
  4001. would like to use also the advantages of these smart pointers. The problem is that
  4002. Boost and C++ TR1 smart pointers are not ready to be used for shared memory. The cause
  4003. is that those smart pointers contain raw pointers and they use virtual functions,
  4004. something that is not possible if you want to place your data in shared memory.
  4005. The virtual function limitation makes even impossible to achieve the same level of
  4006. functionality of Boost and TR1 with [*Boost.Interprocess] smart pointers.
  4007. Interprocess ownership smart pointers are mainly "smart pointers containing smart pointers",
  4008. so we can specify the pointer type they contain.
  4009. [section:intrusive_ptr Intrusive pointer]
  4010. [classref boost::interprocess::intrusive_ptr] is the generalization of `boost::intrusive_ptr<>`
  4011. to allow non-raw pointers as intrusive pointer members. As the well-known
  4012. `boost::intrusive_ptr` we must specify the pointee type but we also must also specify
  4013. the pointer type to be stored in the intrusive_ptr:
  4014. [c++]
  4015. //!The intrusive_ptr class template stores a pointer to an object
  4016. //!with an embedded reference count. intrusive_ptr is parameterized on
  4017. //!T (the type of the object pointed to) and VoidPointer(a void pointer type
  4018. //!that defines the type of pointer that intrusive_ptr will store).
  4019. //!intrusive_ptr<T, void *> defines a class with a T* member whereas
  4020. //!intrusive_ptr<T, offset_ptr<void> > defines a class with a offset_ptr<T> member.
  4021. //!Relies on unqualified calls to:
  4022. //!
  4023. //!void intrusive_ptr_add_ref(T * p);
  4024. //!void intrusive_ptr_release(T * p);
  4025. //!
  4026. //!with (p != 0)
  4027. //!
  4028. //!The object is responsible for destroying itself.
  4029. template<class T, class VoidPointer>
  4030. class intrusive_ptr;
  4031. So `boost::interprocess::intrusive_ptr<MyClass, void*>` is equivalent to
  4032. `boost::intrusive_ptr<MyClass>`. But if we want to place the intrusive_ptr in
  4033. shared memory we must specify a relative pointer type like
  4034. `boost::interprocess::intrusive_ptr<MyClass, boost::interprocess::offset_ptr<void> >`
  4035. [import ../example/doc_intrusive.cpp]
  4036. [doc_intrusive]
  4037. [endsect]
  4038. [section:scoped_ptr Scoped pointer]
  4039. `boost::interprocess::scoped_ptr<>` is the big brother of `boost::scoped_ptr<>`, which
  4040. adds a custom deleter to specify how the pointer passed to the scoped_ptr must be destroyed.
  4041. Also, the `pointer` typedef of the deleter will specify the pointer type stored by scoped_ptr.
  4042. [c++]
  4043. //!scoped_ptr stores a pointer to a dynamically allocated object.
  4044. //!The object pointed to is guaranteed to be deleted, either on destruction
  4045. //!of the scoped_ptr, or via an explicit reset. The user can avoid this
  4046. //!deletion using release().
  4047. //!scoped_ptr is parameterized on T (the type of the object pointed to) and
  4048. //!Deleter (the functor to be executed to delete the internal pointer).
  4049. //!The internal pointer will be of the same pointer type as typename
  4050. //!Deleter::pointer type (that is, if typename Deleter::pointer is
  4051. //!offset_ptr<void>, the internal pointer will be offset_ptr<T>).
  4052. template<class T, class Deleter>
  4053. class scoped_ptr;
  4054. `scoped_ptr<>` comes handy to implement *rollbacks* with exceptions: if an exception
  4055. is thrown or we call `return` in the scope of `scoped_ptr<>` the deleter is
  4056. automatically called so that *the deleter can be considered as a rollback* function.
  4057. If all goes well, we call `release()` member function to avoid rollback when
  4058. the `scoped_ptr` goes out of scope.
  4059. [import ../example/doc_scoped_ptr.cpp]
  4060. [doc_scoped_ptr]
  4061. [endsect]
  4062. [section:shared_ptr Shared pointer and weak pointer]
  4063. [*Boost.Interprocess] also offers the possibility of creating non-intrusive
  4064. reference-counted objects in managed shared memory or mapped files.
  4065. Unlike
  4066. [@http://www.boost.org/libs/smart_ptr/shared_ptr.htm boost::shared_ptr],
  4067. due to limitations of mapped segments [classref boost::interprocess::shared_ptr]
  4068. cannot take advantage of virtual functions to maintain the same shared pointer
  4069. type while providing user-defined allocators and deleters. The allocator
  4070. and the deleter are template parameters of the shared pointer.
  4071. Since the reference count and other auxiliary data needed by
  4072. [classref boost::interprocess::shared_ptr shared_ptr] must be created also in
  4073. the managed segment, and the deleter has to delete the object from
  4074. the segment, the user must specify an allocator object and a deleter object
  4075. when constructing a non-empty instance of
  4076. [classref boost::interprocess::shared_ptr shared_ptr], just like
  4077. [*Boost.Interprocess] containers need to pass allocators in their constructors.
  4078. Here is the declaration of [classref boost::interprocess::shared_ptr shared_ptr]:
  4079. [c++]
  4080. template<class T, class VoidAllocator, class Deleter>
  4081. class shared_ptr;
  4082. * T is the type of the pointed type.
  4083. * VoidAllocator is the allocator to be used to allocate auxiliary
  4084. elements such as the reference count, the deleter...
  4085. The internal `pointer` typedef of the allocator will determine
  4086. the type of pointer that shared_ptr will internally use, so
  4087. allocators defining `pointer` as `offset_ptr<void>` will
  4088. make all internal pointers used by `shared_ptr` to be
  4089. also relative pointers. See [classref boost::interprocess::allocator]
  4090. for a working allocator.
  4091. * Deleter is the function object that will be used to destroy
  4092. the pointed object when the last reference to the object
  4093. is destroyed. The deleter functor will take a pointer to T
  4094. of the same category as the void pointer defined by
  4095. `VoidAllocator::pointer`. See [classref boost::interprocess::deleter]
  4096. for a generic deleter that erases a object from a managed segment.
  4097. With correctly specified parameters, [*Boost.Interprocess] users
  4098. can create objects in shared memory that hold shared pointers pointing
  4099. to other objects also in shared memory, obtaining the benefits of
  4100. reference counting. Let's see how to create a shared pointer in a managed shared memory:
  4101. [import ../example/doc_shared_ptr_explicit.cpp]
  4102. [doc_shared_ptr_explicit]
  4103. [classref boost::interprocess::shared_ptr] is very flexible and
  4104. configurable (we can specify the allocator and the deleter, for example),
  4105. but as shown the creation of a shared pointer in managed segments
  4106. need too much typing.
  4107. To simplify this usage, [classref boost::interprocess::shared_ptr] header
  4108. offers a shared pointer definition helper class
  4109. ([classref boost::interprocess::managed_shared_ptr managed_shared_ptr]) and a function
  4110. ([funcref boost::interprocess::make_managed_shared_ptr make_managed_shared_ptr])
  4111. to easily construct a shared pointer from a type allocated in a managed segment
  4112. with an allocator that will allocate the reference count also in the managed
  4113. segment and a deleter that will erase the object from the segment.
  4114. These utilities will use a [*Boost.Interprocess] allocator
  4115. ([classref boost::interprocess::allocator])
  4116. and deleter ([classref boost::interprocess::deleter]) to do their job.
  4117. The definition of the previous shared pointer
  4118. could be simplified to the following:
  4119. [c++]
  4120. typedef managed_shared_ptr<MyType, managed_shared_memory>::type my_shared_ptr;
  4121. And the creation of a shared pointer can be simplified to this:
  4122. [c++]
  4123. my_shared_ptr sh_ptr = make_managed_shared_ptr
  4124. (segment.construct<MyType>("object to share")(), segment);
  4125. [*Boost.Interprocess] also offers a weak pointer named
  4126. [classref boost::interprocess::weak_ptr weak_ptr] (with its corresponding
  4127. [classref boost::interprocess::managed_weak_ptr managed_weak_ptr] and
  4128. [funcref boost::interprocess::make_managed_weak_ptr make_managed_weak_ptr] utilities)
  4129. to implement non-owning observers of an object owned by
  4130. [classref boost::interprocess::shared_ptr shared_ptr].
  4131. Now let's see a detailed example of the use of
  4132. [classref boost::interprocess::shared_ptr shared_ptr]:
  4133. and
  4134. [classref boost::interprocess::weak_ptr weak_ptr]
  4135. [import ../example/doc_shared_ptr.cpp]
  4136. [doc_shared_ptr]
  4137. In general, using [*Boost.Interprocess]' [classref boost::interprocess::shared_ptr shared_ptr]
  4138. and [classref boost::interprocess::weak_ptr weak_ptr] is very similar to their
  4139. counterparts [@http://www.boost.org/libs/smart_ptr/shared_ptr.htm boost::shared_ptr]
  4140. and [@http://www.boost.org/libs/smart_ptr/weak_ptr.htm boost::weak_ptr], but
  4141. they need more template parameters and more run-time parameters in their constructors.
  4142. Just like [@http://www.boost.org/libs/smart_ptr/shared_ptr.htm boost::shared_ptr]
  4143. can be stored in a STL container, [classref boost::interprocess::shared_ptr shared_ptr]
  4144. can also be stored in [*Boost.Interprocess] containers.
  4145. If a programmer just uses [classref boost::interprocess::shared_ptr shared_ptr]
  4146. to be able to insert dynamically constructed objects into a container constructed
  4147. in the managed segment, but he does not need to share the ownership of that object with
  4148. other objects [classref boost::interprocess::managed_unique_ptr managed_unique_ptr] is a much
  4149. faster and easier to use alternative.
  4150. [endsect]
  4151. [section:unique_ptr Unique pointer]
  4152. Unique ownership smart pointers are really useful to free programmers from
  4153. manual resource liberation of non-shared objects. [*Boost.Interprocess]'
  4154. `unique_ptr` is much like
  4155. [classref boost::interprocess::scoped_ptr scoped_ptr] but it's [*moveable]
  4156. and can be easily inserted in [*Boost.Interprocess] containers.
  4157. Interprocess had its own `unique_ptr` implementation but from Boost 1.57,
  4158. [*Boost.Interprocess] uses the improved and generic `boost::unique_ptr`
  4159. implementation. Here is the declaration of the unique pointer class:
  4160. [c++]
  4161. template <class T, class D>
  4162. class unique_ptr;
  4163. * T is the type of the object pointed by `unique_ptr`.
  4164. * D is the deleter that will erase the object type of the object pointed by
  4165. the unique_ptr when the unique pointer
  4166. is destroyed (and if still has the ownership of the object). If the deleter defines
  4167. an internal `pointer` typedef, `unique_ptr`]
  4168. will use an internal pointer of the same type. So if `D::pointer` is `offset_ptr<T>`
  4169. the unique pointer will store a relative pointer instead of a raw one. This
  4170. allows placing `unique_ptr` in shared
  4171. memory and memory-mapped files.
  4172. `unique_ptr` can release the ownership of
  4173. the stored pointer so it's useful also to be used as a rollback function. One of the main
  4174. properties of the class is that [*is not copyable, but only moveable]. When a unique
  4175. pointer is moved to another one, the ownership of the pointer is transferred from
  4176. the source unique pointer to the target unique pointer. If the target unique pointer
  4177. owned an object, that object is first deleted before taking ownership of the new object.
  4178. [*Boost.Interprocess] also offers auxiliary types to
  4179. easily define and construct unique pointers that can be placed in managed segments
  4180. and will correctly delete owned object from the segment:
  4181. [classref boost::interprocess::managed_unique_ptr managed_unique_ptr]
  4182. and
  4183. [funcref boost::interprocess::make_managed_unique_ptr make_managed_unique_ptr]
  4184. utilities.
  4185. Here we see an example of the use `unique_ptr`
  4186. including creating containers of such objects:
  4187. [import ../example/doc_unique_ptr.cpp]
  4188. [doc_unique_ptr]
  4189. [endsect]
  4190. [endsect]
  4191. [section:architecture Architecture and internals]
  4192. [section:basic_guidelines Basic guidelines]
  4193. When building [*Boost.Interprocess] architecture, I took some basic guidelines that can be
  4194. summarized by these points:
  4195. * [*Boost.Interprocess] should be portable at least in UNIX and Windows systems. That
  4196. means unifying not only interfaces but also behaviour. This is why
  4197. [*Boost.Interprocess] has chosen kernel or filesystem persistence for shared memory
  4198. and named synchronization mechanisms. Process persistence for shared memory is also
  4199. desirable but it's difficult to achieve in UNIX systems.
  4200. * [*Boost.Interprocess] inter-process synchronization primitives should be equal to thread
  4201. synchronization primitives. [*Boost.Interprocess] aims to have an interface compatible
  4202. with the C++ standard thread API.
  4203. * [*Boost.Interprocess] architecture should be modular, customizable but efficient. That's
  4204. why [*Boost.Interprocess] is based on templates and memory algorithms, index types,
  4205. mutex types and other classes are templatizable.
  4206. * [*Boost.Interprocess] architecture should allow the same concurrency as thread based
  4207. programming. Different mutual exclusion levels are defined so that a process
  4208. can concurrently allocate raw memory when expanding a shared memory vector while another
  4209. process can be safely searching a named object.
  4210. * [*Boost.Interprocess] containers know nothing about [*Boost.Interprocess]. All specific
  4211. behaviour is contained in the STL-like allocators. That allows STL vendors to slightly
  4212. modify (or better said, generalize) their standard container implementations and obtain
  4213. a fully std::allocator and boost::interprocess::allocator compatible container. This also
  4214. make [*Boost.Interprocess] containers compatible with standard algorithms.
  4215. [*Boost.Interprocess] is built above 3 basic classes: a [*memory algorithm], a
  4216. [*segment manager] and a [*managed memory segment]:
  4217. [endsect]
  4218. [section:architecture_algorithm_to_managed From the memory algorithm to the managed segment]
  4219. [section:architecture_memory_algorithm The memory algorithm]
  4220. The [*memory algorithm] is an object that is placed in the first bytes of a
  4221. shared memory/memory mapped file segment. The [*memory algorithm] can return
  4222. portions of that segment to users marking them as used and the user can return those
  4223. portions to the [*memory algorithm] so that the [*memory algorithm] mark them as free
  4224. again. There is an exception though: some bytes beyond the end of the memory
  4225. algorithm object, are reserved and can't be used for this dynamic allocation.
  4226. This "reserved" zone will be used to place other additional objects
  4227. in a well-known place.
  4228. To sum up, a [*memory algorithm] has the same mission as malloc/free of
  4229. standard C library, but it just can return portions of the segment
  4230. where it is placed. The layout of a memory segment would be:
  4231. [c++]
  4232. Layout of the memory segment:
  4233. ____________ __________ ____________________________________________
  4234. | | | |
  4235. | memory | reserved | The memory algorithm will return portions |
  4236. | algorithm | | of the rest of the segment. |
  4237. |____________|__________|____________________________________________|
  4238. The [*memory algorithm] takes care of memory synchronizations, just like malloc/free
  4239. guarantees that two threads can call malloc/free at the same time. This is usually
  4240. achieved placing a process-shared mutex as a member of the memory algorithm. Take
  4241. in care that the memory algorithm knows [*nothing] about the segment (if it is
  4242. shared memory, a shared memory file, etc.). For the memory algorithm the segment
  4243. is just a fixed size memory buffer.
  4244. The [*memory algorithm] is also a configuration point for the rest of the
  4245. [*Boost.Interprocess]
  4246. framework since it defines two basic types as member typedefs:
  4247. [c++]
  4248. typedef /*implementation dependent*/ void_pointer;
  4249. typedef /*implementation dependent*/ mutex_family;
  4250. The `void_pointer` typedef defines the pointer type that will be used in the
  4251. [*Boost.Interprocess] framework (segment manager, allocators, containers). If the memory
  4252. algorithm is ready to be placed in a shared memory/mapped file mapped in different base
  4253. addresses, this pointer type will be defined as `offset_ptr<void>` or a similar relative
  4254. pointer. If the [*memory algorithm] will be used just with fixed address mapping,
  4255. `void_pointer` can be defined as `void*`.
  4256. The rest of the interface of a [*Boost.Interprocess] [*memory algorithm] is described in
  4257. [link interprocess.customizing_interprocess.custom_interprocess_alloc Writing a new shared memory allocation algorithm]
  4258. section. As memory algorithm examples, you can see the implementations
  4259. [classref boost::interprocess::simple_seq_fit simple_seq_fit] or
  4260. [classref boost::interprocess::rbtree_best_fit rbtree_best_fit] classes.
  4261. [endsect]
  4262. [section:architecture_segment_manager The segment manager]
  4263. The *segment manager*, is an object also placed in the first bytes of the
  4264. managed memory segment (shared memory, memory mapped file), that offers more
  4265. sophisticated services built above the [*memory algorithm]. How can [*both] the
  4266. segment manager and memory algorithm be placed in the beginning of the segment?
  4267. That's because the segment manager [*owns] the memory algorithm: The
  4268. truth is that the memory algorithm is [*embedded] in the segment manager:
  4269. [c++]
  4270. The layout of managed memory segment:
  4271. _______ _________________
  4272. | | | |
  4273. | some | memory | other |<- The memory algorithm considers
  4274. |members|algorithm|members| "other members" as reserved memory, so
  4275. |_______|_________|_______| it does not use it for dynamic allocation.
  4276. |_________________________|____________________________________________
  4277. | | |
  4278. | segment manager | The memory algorithm will return portions |
  4279. | | of the rest of the segment. |
  4280. |_________________________|____________________________________________|
  4281. The [*segment manager] initializes the memory algorithm and tells the memory
  4282. manager that it should not use the memory where the rest of the
  4283. [*segment manager]'s member are placed for dynamic allocations. The
  4284. other members of the [*segment manager] are [*a recursive mutex]
  4285. (defined by the memory algorithm's [*mutex_family::recursive_mutex] typedef member),
  4286. and [*two indexes (maps)]: one to implement named allocations, and another one to
  4287. implement "unique instance" allocations.
  4288. * The first index is a map with a pointer to a c-string (the name of the named object)
  4289. as a key and a structure with information of the dynamically allocated object
  4290. (the most important being the address and the size of the object).
  4291. * The second index is used to implement "unique instances"
  4292. and is basically the same as the first index,
  4293. but the name of the object comes from a `typeid(T).name()` operation.
  4294. The memory needed to store [name pointer, object information] pairs in the index is
  4295. allocated also via the *memory algorithm*, so we can tell that internal indexes
  4296. are just like ordinary user objects built in the segment. The rest of the memory
  4297. to store the name of the object, the object itself, and meta-data for
  4298. destruction/deallocation is allocated using the *memory algorithm* in a single
  4299. `allocate()` call.
  4300. As seen, the [*segment manager] knows [*nothing] about shared memory/memory mapped files.
  4301. The [*segment manager] itself does not allocate portions of the segment,
  4302. it just asks the *memory algorithm* to allocate the needed memory from the rest
  4303. of the segment. The [*segment manager] is a class built above the memory algorithm
  4304. that offers named object construction, unique instance constructions, and many
  4305. other services.
  4306. The [*segment manager] is implemented in [*Boost.Interprocess] by
  4307. the [classref boost::interprocess::segment_manager segment_manager] class.
  4308. [c++]
  4309. template<class CharType
  4310. ,class MemoryAlgorithm
  4311. ,template<class IndexConfig> class IndexType>
  4312. class segment_manager;
  4313. As seen, the segment manager is quite generic: we can specify the character type
  4314. to be used to identify named objects, we can specify the memory algorithm that will
  4315. control dynamically the portions of the memory segment, and we can specify
  4316. also the index type that will store the [name pointer, object information] mapping.
  4317. We can construct our own index types as explained in
  4318. [link interprocess.customizing_interprocess.custom_indexes Building custom indexes] section.
  4319. [endsect]
  4320. [section:architecture_managed_memory Boost.Interprocess managed memory segments]
  4321. The [*Boost.Interprocess] managed memory segments that construct the shared memory/memory
  4322. mapped file, place there the segment manager and forward the user requests to the
  4323. segment manager. For example, [classref boost::interprocess::basic_managed_shared_memory basic_managed_shared_memory]
  4324. is a [*Boost.Interprocess] managed memory segment that works with shared memory.
  4325. [classref boost::interprocess::basic_managed_mapped_file basic_managed_mapped_file] works with memory mapped files, etc...
  4326. Basically, the interface of a [*Boost.Interprocess] managed memory segment is the same as
  4327. the [*segment manager] but it also offers functions to "open", "create", or "open or create"
  4328. shared memory/memory-mapped files segments and initialize all needed resources.
  4329. Managed memory segment classes are not built in shared memory or memory mapped files, they
  4330. are normal C++ classes that store a pointer to the segment manager (which is built
  4331. in shared memory or memory mapped files).
  4332. Apart from this, managed memory segments offer specific functions: `managed_mapped_file`
  4333. offers functions to flush memory contents to the file, `managed_heap_memory` offers
  4334. functions to expand the memory, etc...
  4335. Most of the functions of [*Boost.Interprocess] managed memory segments can be shared
  4336. between all managed memory segments, since many times they just forward the functions
  4337. to the segment manager. Because of this,
  4338. in [*Boost.Interprocess] all managed memory segments derive from a common class that
  4339. implements memory-independent (shared memory, memory mapped files) functions:
  4340. [@../../boost/interprocess/detail/managed_memory_impl.hpp
  4341. boost::interprocess::ipcdetail::basic_managed_memory_impl]
  4342. Deriving from this class, [*Boost.Interprocess] implements several managed memory
  4343. classes, for different memory backends:
  4344. * [classref boost::interprocess::basic_managed_shared_memory basic_managed_shared_memory] (for shared memory).
  4345. * [classref boost::interprocess::basic_managed_mapped_file basic_managed_mapped_file] (for memory mapped files).
  4346. * [classref boost::interprocess::basic_managed_heap_memory basic_managed_heap_memory] (for heap allocated memory).
  4347. * [classref boost::interprocess::basic_managed_external_buffer basic_managed_external_buffer] (for user provided external buffer).
  4348. [endsect]
  4349. [endsect]
  4350. [section:allocators_containers Allocators and containers]
  4351. [section:allocators Boost.Interprocess allocators]
  4352. The [*Boost.Interprocess] STL-like allocators are fairly simple and follow the usual C++
  4353. allocator approach. Normally, allocators for STL containers are based above new/delete
  4354. operators and above those, they implement pools, arenas and other allocation tricks.
  4355. In [*Boost.Interprocess] allocators, the approach is similar, but all allocators are based
  4356. on the *segment manager*. The segment manager is the only one that provides from simple
  4357. memory allocation to named object creations. [*Boost.Interprocess] allocators always store
  4358. a pointer to the segment manager, so that they can obtain memory from the segment or share
  4359. a common pool between allocators.
  4360. As you can imagine, the member pointers of the allocator are not a raw pointers, but
  4361. pointer types defined by the `segment_manager::void_pointer` type. Apart from this,
  4362. the `pointer` typedef of [*Boost.Interprocess] allocators is also of the same type of
  4363. `segment_manager::void_pointer`.
  4364. This means that if our allocation algorithm defines `void_pointer` as `offset_ptr<void>`,
  4365. `boost::interprocess::allocator<T>` will store an `offset_ptr<segment_manager>`
  4366. to point to the segment manager and the `boost::interprocess::allocator<T>::pointer` type
  4367. will be `offset_ptr<T>`. This way, [*Boost.Interprocess] allocators can be placed in the
  4368. memory segment managed by the segment manager, that is, shared memory, memory mapped files,
  4369. etc...
  4370. [endsect]
  4371. [section:implementation_segregated_storage_pools Implementation of [*Boost.Interprocess] segregated storage pools]
  4372. Segregated storage pools are simple and follow the classic segregated storage algorithm.
  4373. * The pool allocates chunks of memory using the segment manager's raw memory
  4374. allocation functions.
  4375. * The chunk contains a pointer to form a singly linked list of chunks. The pool
  4376. will contain a pointer to the first chunk.
  4377. * The rest of the memory of the chunk is divided in nodes of the requested size and
  4378. no memory is used as payload for each node. Since the memory of a free node
  4379. is not used that memory is used to place a pointer to form a singly linked list of
  4380. free nodes. The pool has a pointer to the first free node.
  4381. * Allocating a node is just taking the first free node from the list. If the list
  4382. is empty, a new chunk is allocated, linked in the list of chunks and the new free
  4383. nodes are linked in the free node list.
  4384. * Deallocation returns the node to the free node list.
  4385. * When the pool is destroyed, the list of chunks is traversed and memory is returned
  4386. to the segment manager.
  4387. The pool is implemented by the
  4388. [@../../boost/interprocess/allocators/detail/node_pool.hpp
  4389. private_node_pool and shared_node_pool] classes.
  4390. [endsect]
  4391. [section:implementation_adaptive_pools Implementation of [*Boost.Interprocess] adaptive pools]
  4392. Adaptive pools are a variation of segregated lists but they have a more complicated
  4393. approach:
  4394. * Instead of using raw allocation, the pool allocates [*aligned] chunks of memory
  4395. using the segment manager. This is an [*essential] feature since a node can reach
  4396. its chunk information applying a simple mask to its address.
  4397. * The chunks contains pointers to form a doubly linked list of chunks and
  4398. an additional pointer to create a singly linked list of free nodes placed
  4399. on that chunk. So unlike the segregated storage algorithm, the free list
  4400. of nodes is implemented [*per chunk].
  4401. * The pool maintains the chunks in increasing order of free nodes. This improves
  4402. locality and minimizes the dispersion of node allocations across the chunks
  4403. facilitating the creation of totally free chunks.
  4404. * The pool has a pointer to the chunk with the minimum (but not zero) free nodes.
  4405. This chunk is called the "active" chunk.
  4406. * Allocating a node is just returning the first free node of the "active" chunk.
  4407. The list of chunks is reordered according to the free nodes count.
  4408. The pointer to the "active" pool is updated if necessary.
  4409. * If the pool runs out of nodes, a new chunk is allocated, and pushed back in the
  4410. list of chunks. The pointer to the "active" pool is updated if necessary.
  4411. * Deallocation returns the node to the free node list of its chunk and updates
  4412. the "active" pool accordingly.
  4413. * If the number of totally free chunks exceeds the limit, chunks are returned
  4414. to the segment manager.
  4415. * When the pool is destroyed, the list of chunks is traversed and memory is returned
  4416. to the segment manager.
  4417. The adaptive pool is implemented by the
  4418. [@../../boost/interprocess/allocators/detail/adaptive_node_pool.hpp
  4419. private_adaptive_node_pool and adaptive_node_pool] classes.
  4420. [endsect]
  4421. [section:architecture_containers Boost.Interprocess containers]
  4422. [*Boost.Interprocess] containers are standard conforming counterparts of STL containers
  4423. in `boost::interprocess` namespace, but with these little details:
  4424. * [*Boost.Interprocess] STL containers don't assume that memory allocated with
  4425. an allocator can be deallocated with other allocator of
  4426. the same type. They always compare allocators with `operator==()`
  4427. to know if this is possible.
  4428. * The pointers of the internal structures of the [*Boost.Interprocess] containers are
  4429. of the same type the `pointer` type defined by the allocator of the container. This
  4430. allows placing containers in managed memory segments mapped in different base addresses.
  4431. [endsect]
  4432. [endsect]
  4433. [section:performance Performance of Boost.Interprocess]
  4434. This section tries to explain the performance characteristics of [*Boost.Interprocess],
  4435. so that you can optimize [*Boost.Interprocess] usage if you need more performance.
  4436. [section:performance_allocations Performance of raw memory allocations]
  4437. You can have two types of raw memory allocations with [*Boost.Interprocess] classes:
  4438. * [*Explicit]: The user calls `allocate()` and `deallocate()` functions of
  4439. managed_shared_memory/managed_mapped_file... managed memory segments. This call is
  4440. translated to a `MemoryAlgorithm::allocate()` function, which means that you
  4441. will need just the time that the memory algorithm associated with the managed memory segment
  4442. needs to allocate data.
  4443. * [*Implicit]: For example, you are using `boost::interprocess::allocator<...>` with
  4444. [*Boost.Interprocess] containers. This allocator calls the same `MemoryAlgorithm::allocate()`
  4445. function than the explicit method, [*every] time a vector/string has to reallocate its
  4446. buffer or [*every] time you insert an object in a node container.
  4447. If you see that memory allocation is a bottleneck in your application, you have
  4448. these alternatives:
  4449. * If you use map/set associative containers, try using `flat_map` family instead
  4450. of the map family if you mainly do searches and the insertion/removal is mainly done
  4451. in an initialization phase. The overhead is now when the ordered vector has to
  4452. reallocate its storage and move data. You can also call the `reserve()` method
  4453. of these containers when you know beforehand how much data you will insert.
  4454. However in these containers iterators are invalidated in insertions so this
  4455. substitution is only effective in some applications.
  4456. * Use a [*Boost.Interprocess] pooled allocator for node containers, because pooled
  4457. allocators call `allocate()` only when the pool runs out of nodes. This is pretty
  4458. efficient (much more than the current default general-purpose algorithm) and this
  4459. can save a lot of memory. See
  4460. [link interprocess.allocators_containers.stl_allocators_segregated_storage Segregated storage node allocators] and
  4461. [link interprocess.allocators_containers.stl_allocators_adaptive Adaptive node allocators] for more information.
  4462. * Write your own memory algorithm. If you have experience with memory allocation algorithms
  4463. and you think another algorithm is better suited than the default one for your application,
  4464. you can specify it in all [*Boost.Interprocess] managed memory segments. See the section
  4465. [link interprocess.customizing_interprocess.custom_interprocess_alloc Writing a new shared memory allocation algorithm]
  4466. to know how to do this. If you think its better than the default one for general-purpose
  4467. applications, be polite and donate it to [*Boost.Interprocess] to make it default!
  4468. [endsect]
  4469. [section:performance_named_allocation Performance of named allocations]
  4470. [*Boost.Interprocess] allows the same parallelism as two threads writing to a common
  4471. structure, except when the user creates/searches named/unique objects. The steps
  4472. when creating a named object are these:
  4473. * Lock a recursive mutex (so that you can make named allocations inside
  4474. the constructor of the object to be created).
  4475. * Try to insert the [name pointer, object information] in the name/object index.
  4476. This lookup has to assure that the name has not been used before.
  4477. This is achieved calling `insert()` function in the index. So the time this
  4478. requires is dependent on the index type (ordered vector, tree, hash...).
  4479. This can require a call to the memory algorithm allocation function if
  4480. the index has to be reallocated, it's a node allocator, uses pooled allocations...
  4481. * Allocate a single buffer to hold the name of the object, the object itself,
  4482. and meta-data for destruction (number of objects, etc...).
  4483. * Call the constructors of the object being created. If it's an array, one
  4484. constructor per array element.
  4485. * Unlock the recursive mutex.
  4486. The steps when destroying a named object using the name of the object
  4487. (`destroy<T>(name)`) are these:
  4488. * Lock a recursive mutex .
  4489. * Search in the index the entry associated to that name. Copy that information and
  4490. erase the index entry. This is done using `find(const key_type &)` and `erase(iterator)`
  4491. members of the index. This can require element reordering if the index is a
  4492. balanced tree, an ordered vector...
  4493. * Call the destructor of the object (many if it's an array).
  4494. * Deallocate the memory buffer containing the name, metadata and the object itself
  4495. using the allocation algorithm.
  4496. * Unlock the recursive mutex.
  4497. The steps when destroying a named object using the pointer of the object
  4498. (`destroy_ptr(T *ptr)`) are these:
  4499. * Lock a recursive mutex .
  4500. * Depending on the index type, this can be different:
  4501. * If the index is a node index, (marked with `boost::interprocess::is_node_index`
  4502. specialization): Take the iterator stored near the object and call
  4503. `erase(iterator)`. This can require element reordering if the index is a
  4504. balanced tree, an ordered vector...
  4505. * If it's not an node index: Take the name stored near the object and erase
  4506. the index entry calling `erase(const key &). This can require element reordering
  4507. if the index is a balanced tree, an ordered vector...
  4508. * Call the destructor of the object (many if it's an array).
  4509. * Deallocate the memory buffer containing the name, metadata and the object itself
  4510. using the allocation algorithm.
  4511. * Unlock the recursive mutex.
  4512. If you see that the performance is not good enough you have these alternatives:
  4513. * Maybe the problem is that the lock time is too big and it hurts parallelism.
  4514. Try to reduce the number of named objects in the global index and if your
  4515. application serves several clients try to build a new managed memory segment
  4516. for each one instead of using a common one.
  4517. * Use another [*Boost.Interprocess] index type if you feel the default one is
  4518. not fast enough. If you are not still satisfied, write your own index type. See
  4519. [link interprocess.customizing_interprocess.custom_indexes Building custom indexes] for this.
  4520. * Destruction via pointer is at least as fast as using the name of the object and
  4521. can be faster (in node containers, for example). So if your problem is that you
  4522. make at lot of named destructions, try to use the pointer. If the index is a
  4523. node index you can save some time.
  4524. [endsect]
  4525. [endsect]
  4526. [endsect]
  4527. [section:customizing_interprocess Customizing Boost.Interprocess]
  4528. [section:custom_interprocess_alloc Writing a new shared memory allocation algorithm]
  4529. If the default algorithm does not satisfy user requirements,
  4530. it's easy to provide different algorithms like bitmapping or
  4531. more advanced segregated lists to meet requirements. The class implementing
  4532. the algorithm must be compatible with shared memory, so it shouldn't have any
  4533. virtual function or virtual inheritance or
  4534. any indirect base class with virtual function or inheritance.
  4535. This is the interface to be implemented:
  4536. [c++]
  4537. class my_algorithm
  4538. {
  4539. public:
  4540. //!The mutex type to be used by the rest of Interprocess framework
  4541. typedef implementation_defined mutex_family;
  4542. //!The pointer type to be used by the rest of Interprocess framework
  4543. typedef implementation_defined void_pointer;
  4544. //!Constructor. "size" is the total size of the managed memory segment,
  4545. //!"extra_hdr_bytes" indicates the extra bytes after the sizeof(my_algorithm)
  4546. //!that the allocator should not use at all.
  4547. my_algorithm (std::size_t size, std::size_t extra_hdr_bytes);
  4548. //!Obtains the minimum size needed by the algorithm
  4549. static std::size_t get_min_size (std::size_t extra_hdr_bytes);
  4550. //!Allocates bytes, returns 0 if there is not more memory
  4551. void* allocate (std::size_t nbytes);
  4552. //!Deallocates previously allocated bytes
  4553. void deallocate (void *adr);
  4554. //!Returns the size of the memory segment
  4555. std::size_t get_size() const;
  4556. //!Increases managed memory in extra_size bytes more
  4557. void grow(std::size_t extra_size);
  4558. /*...*/
  4559. };
  4560. Let's see the public typedefs to define:
  4561. [c++]
  4562. typedef /* . . . */ void_pointer;
  4563. typedef /* . . . */ mutex_family;
  4564. The `void_pointer` typedef specifies the pointer type to be used in
  4565. the [*Boost.Interprocess] framework that uses the algorithm. For example, if we define
  4566. [c++]
  4567. typedef void * void_pointer;
  4568. all [*Boost.Interprocess] framework using this algorithm will use raw pointers as members.
  4569. But if we define:
  4570. [c++]
  4571. typedef offset_ptr<void> void_pointer;
  4572. then all [*Boost.Interprocess] framework will use relative pointers.
  4573. The `mutex_family` is a structure containing typedefs
  4574. for different interprocess_mutex types to be used in the [*Boost.Interprocess]
  4575. framework. For example the defined
  4576. [c++]
  4577. struct mutex_family
  4578. {
  4579. typedef boost::interprocess::interprocess_mutex mutex_type;
  4580. typedef boost::interprocess::interprocess_recursive_mutex recursive_mutex_type;
  4581. };
  4582. defines all interprocess_mutex types using boost::interprocess interprocess_mutex types.
  4583. The user can specify the desired mutex family.
  4584. [c++]
  4585. typedef mutex_family mutex_family;
  4586. The new algorithm (let's call it *my_algorithm*) must implement all the functions
  4587. that boost::interprocess::rbtree_best_fit class offers:
  4588. * [*my_algorithm]'s constructor must take 2 arguments:
  4589. * [*size] indicates the total size of the managed memory segment, and
  4590. [*my_algorithm] object will be always constructed a at offset 0
  4591. of the memory segment.
  4592. * The [*extra_hdr_bytes] parameter indicates the number of bytes after
  4593. the offset `sizeof(my_algorithm)` that [*my_algorithm] can't use at all. This extra
  4594. bytes will be used to store additional data that should not be overwritten.
  4595. So, [*my_algorithm] will be placed at address XXX of the memory segment, and will
  4596. manage the [*[XXX + sizeof(my_algorithm) + extra_hdr_bytes, XXX + size)] range of
  4597. the segment.
  4598. * The [*get_min_size()] function should return the minimum space the algorithm
  4599. needs to be valid with the passed [*extra_hdr_bytes] parameter. This function will
  4600. be used to check if the memory segment is big enough to place the algorithm there.
  4601. * The [*allocate()] function must return 0 if there is no more available memory.
  4602. The memory returned by [*my_algorithm]
  4603. must be aligned to the most restrictive memory alignment of the system.
  4604. This function should be executed with the synchronization capabilities offered
  4605. by `typename mutex_family::mutex_type` interprocess_mutex. That means, that if we define
  4606. `typedef mutex_family mutex_family;` then this function should offer
  4607. the same synchronization as if it was surrounded by an interprocess_mutex lock/unlock.
  4608. Normally, this is implemented using a member of type `mutex_family::mutex_type`, but
  4609. it could be done using atomic instructions or lock free algorithms.
  4610. * The [*deallocate()] function must make the returned buffer available for new
  4611. allocations. This function should offer the same synchronization as `allocate()`.
  4612. * The [*size()] function will return the passed [*size] parameter in the constructor.
  4613. So, [*my_algorithm] should store the size internally.
  4614. * The [*grow()] function will expand the managed memory by [*my_algorithm] in [*extra_size]
  4615. bytes. So [*size()] function should return the updated size,
  4616. and the new managed memory range will be (if the address where the algorithm is
  4617. constructed is XXX): [*[XXX + sizeof(my_algorithm) + extra_hdr_bytes, XXX + old_size + extra_size)].
  4618. This function should offer the same synchronization as `allocate()`.
  4619. That's it. Now we can create new managed shared memory that uses our new algorithm:
  4620. [c++]
  4621. //Managed memory segment to allocate named (c-string) objects
  4622. //using a user-defined memory allocation algorithm
  4623. basic_managed_shared_memory<char,
  4624. ,my_algorithm
  4625. ,flat_map_index>
  4626. my_managed_shared_memory;
  4627. [endsect]
  4628. [section:custom_allocators Building custom STL compatible allocators for Boost.Interprocess]
  4629. If provided STL-like allocators don't satisfy user needs, the user
  4630. can implement another STL compatible allocator using raw memory allocation
  4631. and named object construction functions.
  4632. The user can this way implement more suitable allocation
  4633. schemes on top of basic shared memory allocation schemes,
  4634. just like more complex allocators are built on top of
  4635. new/delete functions.
  4636. When using a managed memory segment, [*get_segment_manager()]
  4637. function returns a pointer to the segment manager. With this pointer,
  4638. the raw memory allocation and named object construction functions can be
  4639. called directly:
  4640. [c++]
  4641. //Create the managed shared memory and initialize resources
  4642. managed_shared_memory segment
  4643. (create_only
  4644. ,"/MySharedMemory" //segment name
  4645. ,65536); //segment size in bytes
  4646. //Obtain the segment manager
  4647. managed_shared_memory::segment_manager *segment_mngr
  4648. = segment.get_segment_manager();
  4649. //With the segment manager, now we have access to all allocation functions
  4650. segment_mngr->deallocate(segment_mngr->allocate(32));
  4651. segment_mngr->construct<int>("My_Int")[32](0);
  4652. segment_mngr->destroy<int>("My_Int");
  4653. //Initialize the custom, managed memory segment compatible
  4654. //allocator with the segment manager.
  4655. //
  4656. //MySTLAllocator uses segment_mngr->xxx functions to
  4657. //implement its allocation scheme
  4658. MySTLAllocator<int> stl_alloc(segment_mngr);
  4659. //Alias a new vector type that uses the custom STL compatible allocator
  4660. typedef std::vector<int, MySTLAllocator<int> > MyVect;
  4661. //Construct the vector in shared memory with the allocator as constructor parameter
  4662. segment.construct<MyVect>("MyVect_instance")(stl_alloc);
  4663. The user can create new STL compatible allocators that use the segment manager to access
  4664. to all memory management/object construction functions. All [*Boost.Interprocess]' STL
  4665. compatible allocators are based on this approach. [*Remember] that to be compatible with
  4666. managed memory segments, allocators should define their *pointer* typedef as the same
  4667. pointer family as `segment_manager::void_pointer` typedef. This means that if `segment_manager::void_pointer` is
  4668. `offset_ptr<void>`, `MySTLAllocator<int>` should define `pointer` as `offset_ptr<int>`. The
  4669. reason for this is that allocators are members of containers, and if we want to put
  4670. the container in a managed memory segment, the allocator should be ready for that.
  4671. [endsect]
  4672. [section:custom_indexes Building custom indexes]
  4673. The managed memory segment uses a name/object index to
  4674. speed up object searching and creation. Default specializations of
  4675. managed memory segments (`managed_shared_memory` for example),
  4676. use `boost::interprocess::flat_map` as index.
  4677. However, the index type can be chosen via template parameter, so that
  4678. the user can define its own index type if he needs that. To construct
  4679. a new index type, the user must create a class with the following guidelines:
  4680. * The interface of the index must follow the common public interface of std::map
  4681. and std::tr1::unordered_map including public typedefs.
  4682. The `value_type` typedef can be of type:
  4683. [c++]
  4684. std::pair<key_type, mapped_type>
  4685. or
  4686. [c++]
  4687. std::pair<const key_type, mapped_type>
  4688. so that ordered arrays or deques can be used as index types.
  4689. Some known classes following this basic interface are `boost::unordered_map`,
  4690. `boost::interprocess::flat_map` and `boost::interprocess::map`.
  4691. * The class must be a class template taking only a traits struct of this type:
  4692. [c++]
  4693. struct index_traits
  4694. {
  4695. typedef /*...*/ key_type;
  4696. typedef /*...*/ mapped_type;
  4697. typedef /*...*/ segment_manager;
  4698. };
  4699. [c++]
  4700. template <class IndexTraits>
  4701. class my_index_type;
  4702. The `key_type` typedef of the passed `index_traits` will be a specialization of the
  4703. following class:
  4704. [c++]
  4705. //!The key of the named allocation information index. Stores a to
  4706. //!a null string and the length of the string to speed up sorting
  4707. template<...>
  4708. struct index_key
  4709. {
  4710. typedef /*...*/ char_type;
  4711. typedef /*...*/ const_char_ptr_t;
  4712. //Pointer to the object's name (null terminated)
  4713. const_char_ptr_t mp_str;
  4714. //Length of the name buffer (null NOT included)
  4715. std::size_t m_len;
  4716. //!Constructor of the key
  4717. index_key (const CharT *name, std::size_t length);
  4718. //!Less than function for index ordering
  4719. bool operator < (const index_key & right) const;
  4720. //!Equal to function for index ordering
  4721. bool operator == (const index_key & right) const;
  4722. };
  4723. The `mapped_type` is not directly modified by the customized index but it is needed to
  4724. define the index type. The *segment_manager* will be the type of the segment manager that
  4725. will manage the index. `segment_manager` will define interesting internal types like
  4726. `void_pointer` or `mutex_family`.
  4727. * The constructor of the customized index type must take a pointer to segment_manager
  4728. as constructor argument:
  4729. [c++]
  4730. constructor(segment_manager *segment_mngr);
  4731. * The index must provide a memory reservation function, that optimizes the index if the
  4732. user knows the number of elements to be inserted in the index:
  4733. [c++]
  4734. void reserve(std::size_t n);
  4735. For example, the index type `flat_map_index` based in `boost::interprocess::flat_map`
  4736. is just defined as:
  4737. [import ../../../boost/interprocess/indexes/flat_map_index.hpp]
  4738. [flat_map_index]
  4739. If the user is defining a node container based index (a container whose iterators
  4740. are not invalidated when inserting or erasing other elements), [*Boost.Interprocess] can
  4741. optimize named object destruction when destructing via pointer. [*Boost.Interprocess] can
  4742. store an iterator next to the object and instead of using the name of the object to erase
  4743. the index entry, it uses the iterator, which is a faster operation. So if you are creating
  4744. a new node container based index (for example, a tree), you should define an
  4745. specialization of `boost::interprocess::is_node_index<...>` defined in
  4746. `<boost/interprocess/detail/utilities.hpp>`:
  4747. [c++]
  4748. //!Trait classes to detect if an index is a node
  4749. //!index. This allows more efficient operations
  4750. //!when deallocating named objects.
  4751. template<class MapConfig>
  4752. struct is_node_index
  4753. <my_index<MapConfig> >
  4754. {
  4755. static const bool value = true;
  4756. };
  4757. Interprocess also defines other index types:
  4758. * [*boost::map_index] uses *boost::interprocess::map* as index type.
  4759. * [*boost::null_index] that uses an dummy index type if the user just needs
  4760. anonymous allocations and wants to save some space and class instantiations.
  4761. Defining a new managed memory segment that uses the new index is easy. For
  4762. example, a new managed shared memory that uses the new index:
  4763. [c++]
  4764. //!Defines a managed shared memory with a c-strings as
  4765. //!a keys, the red-black tree best fit algorithm (with process-shared mutexes
  4766. //!and offset_ptr pointers) as raw shared memory management algorithm
  4767. //!and a custom index
  4768. typedef
  4769. basic_managed_shared_memory <
  4770. char,
  4771. rbtree_best_fit<mutex_family>,
  4772. my_index_type
  4773. >
  4774. my_managed_shared_memory;
  4775. [endsect]
  4776. [endsect]
  4777. [section:acknowledgements_notes Acknowledgements, notes and links]
  4778. [section:notes_windows Notes for Windows users]
  4779. [section:notes_windows_com_init COM Initialization]
  4780. [*Boost.Interprocess] uses the Windows COM library to implement some features and initializes
  4781. it with concurrency model `COINIT_APARTMENTTHREADED`.
  4782. If the COM library was already initialized by the calling thread for another concurrency model, [*Boost.Interprocess]
  4783. handles this gracefully and uses COM calls for the already initialized model. If for some reason, you
  4784. want [*Boost.Interprocess] to initialize the COM library with another model, define the macro
  4785. `BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL` before including [*Boost.Interprocess] to one of these values:
  4786. * `COINIT_APARTMENTTHREADED_BIPC`
  4787. * `COINIT_MULTITHREADED_BIPC`
  4788. * `COINIT_DISABLE_OLE1DDE_BIPC`
  4789. * `COINIT_SPEED_OVER_MEMORY_BIPC`
  4790. [endsect]
  4791. [section:notes_windows_shm_folder Shared memory emulation folder]
  4792. Shared memory (`shared_memory_object`) is implemented in Windows using memory mapped files, placed in a
  4793. shared directory in the shared documents folder (`SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Common AppData`).
  4794. This directory name is the last bootup time obtained via COM calls (if `BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME`) defined
  4795. or searching the system log for a startup event (the default implementation), so that each bootup shared memory is created in a new
  4796. folder obtaining kernel persistence shared memory.
  4797. If using `BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME`, due to COM implementation related errors,
  4798. in Boost 1.48 & Boost 1.49 the bootup-time folder was dumped and files
  4799. were directly created in shared documents folder, reverting to filesystem persistence shared memory. Boost 1.50 fixed those issues
  4800. and recovered bootup time directory and kernel persistence. If you need to reproduce Boost 1.48 & Boost 1.49 behaviour to communicate
  4801. with applications compiled with that version, comment `#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME` directive
  4802. in the Windows configuration part of `boost/interprocess/detail/workaround.hpp`.
  4803. If using the default implementation, (`BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME` undefined) and the Startup Event is not
  4804. found, this might be due to some buggy software that floods or erases the event log.
  4805. In any error case (shared documents folder is not defined or bootup time could not be obtained, the library throws an error. You still
  4806. can use [*Boost.Interprocess] defining your own directory as the shared directory. When your shared directory is a compile-time constant,
  4807. define `BOOST_INTERPROCESS_SHARED_DIR_PATH` when using the library and that path will be used to place shared memory files. When you have
  4808. to determine the shared directory at runtime, define `BOOST_INTERPROCESS_SHARED_DIR_FUNC` and implement the function
  4809. [c++]
  4810. namespace boost {
  4811. namespace interprocess {
  4812. namespace ipcdetail {
  4813. void get_shared_dir(std::string &shared_dir);
  4814. }
  4815. }
  4816. }
  4817. [endsect]
  4818. [section:boost_use_windows_h BOOST_USE_WINDOWS_H support]
  4819. If `BOOST_USE_WINDOWS_H` is defined, <windows.h> and other windows SDK files are included,
  4820. otherwise the library declares needed functions and structures to reduce the impact of including
  4821. those heavy headers.
  4822. [endsect]
  4823. [endsect]
  4824. [section:notes_linux Notes for Linux users]
  4825. [section:notes_linux_shm_folder Shared memory emulation folder]
  4826. On systems without POSIX shared memory support, shared memory objects are implemented as memory mapped files, using a directory
  4827. placed in "/tmp" that can include (if `BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME` is defined) the last bootup time (if the OS supports it).
  4828. As in Windows, in any error case obtaining this directory the library throws an error . When your shared directory is a compile-time constant,
  4829. define `BOOST_INTERPROCESS_SHARED_DIR_PATH` when using the library and that path will be used to place shared memory files. When you have
  4830. to determine the shared directory at runtime, define `BOOST_INTERPROCESS_SHARED_DIR_FUNC` and implement the function
  4831. [c++]
  4832. namespace boost {
  4833. namespace interprocess {
  4834. namespace ipcdetail {
  4835. void get_shared_dir(std::string &shared_dir);
  4836. }
  4837. }
  4838. }
  4839. [endsect]
  4840. [section:notes_linux_overcommit Overcommit]
  4841. The committed address space is the total amount of virtual memory (swap or physical memory/RAM) that the kernel might have to supply
  4842. if all applications decide to access all of the memory they've requested from the kernel.
  4843. By default, Linux allows processes to commit more virtual memory than available in the system. If that memory is not
  4844. accessed, no physical memory + swap is actually used.
  4845. The reason for this behaviour is that Linux tries to optimize memory usage on forked processes; fork() creates a full copy of
  4846. the process space, but with overcommitted memory, in this new forked instance only pages which have been written to actually need
  4847. to be allocated by the kernel. If applications access more memory than available, then the kernel must free memory in the hard way:
  4848. the OOM (Out Of Memory)-killer picks some processes to kill in order to recover memory.
  4849. [*Boost.Interprocess] has no way to change this behaviour and users might suffer the OOM-killer when accessing shared memory.
  4850. According to the [@http://www.kernel.org/doc/Documentation/vm/overcommit-accounting Kernel documentation], the
  4851. Linux kernel supports several overcommit modes. If you need non-kill guarantees in your application, you should
  4852. change this overcommit behaviour.
  4853. [endsect]
  4854. [endsect]
  4855. [section:thanks_to Thanks to...]
  4856. Many people have contributed with ideas and revisions, so this is the place to
  4857. thank them:
  4858. * Thanks to all people who have shown interest in the library and have downloaded
  4859. and tested the snapshots.
  4860. * Thanks to [*Francis Andre] and [*Anders Hybertz] for their ideas and suggestions.
  4861. Many of them are not implemented yet but I hope to include them when library gets some stability.
  4862. * Thanks to [*Matt Doyle], [*Steve LoBasso], [*Glenn Schrader], [*Hiang Swee Chiang],
  4863. [*Phil Endecott], [*Rene Rivera],
  4864. [*Harold Pirtle], [*Paul Ryan],
  4865. [*Shumin Wu], [*Michal Wozniak], [*Peter Johnson],
  4866. [*Alex Ott], [*Shane Guillory], [*Steven Wooding]
  4867. and [*Kim Barrett] for their bug fixes and library testing.
  4868. * Thanks to [*Martin Adrian] who suggested the use of Interprocess framework for user defined buffers.
  4869. * Thanks to [*Synge Todo] for his boostbook-doxygen patch to improve Interprocess documentation.
  4870. * Thanks to [*Olaf Krzikalla] for his Intrusive library. I have taken some ideas to
  4871. improve red black tree implementation from his library.
  4872. * Thanks to [*Daniel James] for his unordered_map/set family and his help with allocators.
  4873. His great unordered implementation has been a reference to design exception safe containers.
  4874. * Thanks to [*Howard Hinnant] for his amazing help, specially explaining allocator swapping,
  4875. move semantics and for developing upgradable mutex and lock transfer features.
  4876. * Thanks to [*Pavel Vozenilek] for his continuous review process, suggestions, code and
  4877. help. He is the major supporter of Interprocess library. The library has grown with his
  4878. many and great advices.
  4879. * And finally, thank you to all Boosters. [*Long live to C++!]
  4880. [endsect]
  4881. [section:release_notes Release Notes]
  4882. [section:release_notes_boost_1_71_00 Boost 1.71 Release]
  4883. * Fixed bugs:
  4884. * [@https://github.com/boostorg/interprocess/pull/85 GitHub #85 (['"warning: Implicit conversion loses integer precision"])].
  4885. * [@https://github.com/boostorg/interprocess/pull/86 GitHub #86 (['"warning: Possible misuse of comma operator"])].
  4886. [endsect]
  4887. [section:release_notes_boost_1_70_00 Boost 1.70 Release]
  4888. * Fixed bugs:
  4889. * [@https://github.com/boostorg/interprocess/pull/51 GitHub Pull #51 (['"United handling of wait_for_single_object"])].
  4890. * [@https://github.com/boostorg/interprocess/pull/78 GitHub Pull #78 (['"Fix -Wextra-semi clang warnings"])].
  4891. [endsect]
  4892. [section:release_notes_boost_1_69_00 Boost 1.69 Release]
  4893. * Deprecated GCC < 4.3 and MSVC < 9.0 (Visual 2008) compilers.
  4894. * Fixed bugs:
  4895. * [@https://github.com/boostorg/interprocess/issues/59 GitHub Issue #59 (['"warning: ISO C++ prohibits anonymous structs [-Wpedantic]"])].
  4896. * [@https://github.com/boostorg/interprocess/issues/60 GitHub Issue #60 (['"warning: cast between incompatible function types from boost::interprocess::winapi::farproc_t..."])].
  4897. * [@https://github.com/boostorg/interprocess/issues/61 GitHub Issue #61 (['"warning: struct winapi::*_BIPC has virtual functions and accessible non-virtual destructor"])].
  4898. * [@https://github.com/boostorg/interprocess/issues/64 GitHub Issue #64 (['"UBSan: runtime error: load of value 4294967295, (...) for type 'boost::interprocess::mode_t'"])].
  4899. * [@https://github.com/boostorg/interprocess/pull/68 GitHub Pull #68 (['"Prepare for C++20 and remove "throw()" usage"])].
  4900. * [@https://github.com/boostorg/interprocess/pull/70 GitHub Pull #70 (['"Fix deadlock in named_condition::notify_one"])].
  4901. [endsect]
  4902. [section:release_notes_boost_1_68_00 Boost 1.68 Release]
  4903. * Fixed bugs:
  4904. * [@https://github.com/boostorg/interprocess/issues/53 GitHub Issue #53 (['"Crash waiting on condition variable from multiple processes in do_wait()"])].
  4905. * [@https://github.com/boostorg/interprocess/issues/54 GitHub Issue #54 (['"fill_system_message() ignores an error returned by winapi::format_message()"])].
  4906. [endsect]
  4907. [section:release_notes_boost_1_67_00 Boost 1.67 Release]
  4908. * Fixed bugs:
  4909. * [@https://github.com/boostorg/interprocess/pull/45 GitHub Pull #45 (['"Make intrusive_ptr move constructible/assignable"])].
  4910. * [@https://github.com/boostorg/interprocess/pull/48 GitHub Pull #48 (['"Win32: Fix read of reg_expand_sz type"])].
  4911. [endsect]
  4912. [section:release_notes_boost_1_66_00 Boost 1.66 Release]
  4913. * Fixed bugs:
  4914. * [@https://github.com/boostorg/interprocess/pull/41 GitHub Pull #41 (['"Data race in boost::interprocess::rbtree_best_fit"])].
  4915. [endsect]
  4916. [section:release_notes_boost_1_65_00 Boost 1.65 Release]
  4917. * Fixed bugs:
  4918. * [@https://github.com/boostorg/interprocess/pull/37 GitHub Pull #37 (['"Conditionally replace deprecated/removed std::auto_ptr..."])].
  4919. [endsect]
  4920. [section:release_notes_boost_1_64_00 Boost 1.64 Release]
  4921. * Fixed bugs:
  4922. * [@https://svn.boost.org/trac/boost/ticket/12617 Trac #12617 (['"clock_gettime not available on OS X 10.11"])].
  4923. * [@https://svn.boost.org/trac/boost/ticket/12744 Trac #12744 (['"winapi::set_timer_resolution inadvertently changes timer resolution (Windows)"])].
  4924. * [@https://github.com/boostorg/interprocess/pull/32 GitHub Pull #32 (['"Conform to std::pointer_traits requirements"])].
  4925. * [@https://github.com/boostorg/interprocess/pull/33 GitHub Pull #33 (['"explicit cast to derived class" and "64/32 bit processes sharing"])].
  4926. * [@https://github.com/boostorg/interprocess/pull/34 GitHub Pull #34 (['"Update example to use multi_index::member instead of BOOST_MULTI_INDEX_MEMBER"])].
  4927. * [@https://github.com/boostorg/interprocess/pull/35 GitHub Pull #35 (['"Fixed options for cross-compilation"])].
  4928. * New experimental option `BOOST_INTERPROCESS_BOOTSTAMP_IS_SESSION_MANAGER_BASED` from Windows systems.
  4929. This option derives the unique bootstamp used to name the folder where shared memory is placed from registry values associated
  4930. with the session manager. This option only works on Vista and later systems and might be more stable than the default version.
  4931. [endsect]
  4932. [section:release_notes_boost_1_63_00 Boost 1.63 Release]
  4933. * Fixed bugs:
  4934. * [@https://svn.boost.org/trac/boost/ticket/12499 Trac #12499 (['"Memory allocation fails"])].
  4935. * [@https://github.com/boostorg/interprocess/pull/30 GitHub Pull #30 (['"Provide extension point so library user can provide default temp folder"])].
  4936. * [@https://github.com/boostorg/interprocess/pull/31 GitHub Pull #31 (['"Add xsi_key(key_t) constructor"])].
  4937. [endsect]
  4938. [section:release_notes_boost_1_62_00 Boost 1.62 Release]
  4939. * Fixed bugs:
  4940. * [@https://github.com/boostorg/interprocess/pull/27 GitHub Pull #27 (['"Fix undefined behavior"])].
  4941. [endsect]
  4942. [section:release_notes_boost_1_61_00 Boost 1.61 Release]
  4943. * Fixed bugs:
  4944. * [@https://github.com/boostorg/interprocess/pull/23 GitHub Pull #23 (['"Fixed case sensitive for linux mingw"])].
  4945. [endsect]
  4946. [section:release_notes_boost_1_60_00 Boost 1.60 Release]
  4947. * Improved [classref boost::interprocess::offset_ptr offset_ptr] performance and removed any undefined behaviour. No
  4948. special cases needed for different compilers.
  4949. * Fixed bugs:
  4950. * [@https://svn.boost.org/trac/boost/ticket/11699 Trac #11699 (['"Forward declarations of std templates causes stack corruption under Visual Studio 2015"])].
  4951. [endsect]
  4952. [section:release_notes_boost_1_59_00 Boost 1.59 Release]
  4953. * Fixed bugs:
  4954. * [@https://svn.boost.org/trac/boost/ticket/5139 Trac #5139 (['"Initial Stream Position in Boost.Interprocess.Vectorstream"])].
  4955. * [@https://github.com/boostorg/interprocess/pull/19 GitHub Pull #19 (['"Fix exception visibility"])]. Thanks to Romain-Geissler.
  4956. [endsect]
  4957. [section:release_notes_boost_1_58_00 Boost 1.58 Release]
  4958. * Reduced some compile-time dependencies. Updated to Boost.Container changes.
  4959. * Fixed bugs:
  4960. * [@https://github.com/boostorg/interprocess/pull/13 GitHub Pull #13 (['"haiku: we don't have XSI shared memory, so don't try to use it"])].
  4961. Thanks to Jessica Hamilton.
  4962. [endsect]
  4963. [section:release_notes_boost_1_57_00 Boost 1.57 Release]
  4964. * Removed `unique_ptr`, now forwards boost::interprocess::unique_ptr to the general purpose
  4965. `boost::movelib::unique_ptr` class from [*Boost.Move]. This implementation is closer to the standard
  4966. `std::unique_ptr` implementation and it's better maintained.
  4967. * Fixed bugs:
  4968. * [@https://svn.boost.org/trac/boost/ticket/10262 Trac #10262 (['"AIX 6.1 bug with variable definition hz"])].
  4969. * [@https://svn.boost.org/trac/boost/ticket/10229 Trac #10229 (['"Compiling errors in interprocess\detail\os_file_functions.hpp"])].
  4970. * [@https://svn.boost.org/trac/boost/ticket/10506 Trac #10506 (['"Infinite loop in create_or_open_file"])].
  4971. * [@https://github.com/boostorg/interprocess/pull/11 GitHub Pull #11 (['"Compile fix for BOOST_USE_WINDOWS_H"])].
  4972. * Reorganized Doxygen marks to obtain a better header reference.
  4973. [endsect]
  4974. [section:release_notes_boost_1_56_00 Boost 1.56 Release]
  4975. * Fixed bugs:
  4976. * [@https://svn.boost.org/trac/boost/ticket/9221 Trac #9221 (['"message_queue deadlock on linux"])].
  4977. * [@https://svn.boost.org/trac/boost/ticket/9226 Trac #9226 (['"On some computers, Common Appdata is empty in registry, so boost interprocess cannot work"])].
  4978. * [@https://svn.boost.org/trac/boost/ticket/9262 Trac #9262 (['"windows_intermodule_singleton breaks when calling a Debug dll from a Release executable"])].
  4979. * [@https://svn.boost.org/trac/boost/ticket/9284 Trac #9284 (['"WaitForSingleObject(mutex) must handle WAIT_ABANDONED"])].
  4980. * [@https://svn.boost.org/trac/boost/ticket/9285 Trac #9285 (['"CreateMutex returns NULL if fails"])].
  4981. * [@https://svn.boost.org/trac/boost/ticket/9288 Trac #9288 (['"timed_wait does not check if it has expired"])].
  4982. * [@https://svn.boost.org/trac/boost/ticket/9408 Trac #9408 (['"Android does not support XSI_SHARED_MEMORY_OBJECTS"]]).
  4983. * [@https://svn.boost.org/trac/boost/ticket/9729 Trac #9729 (['"crash on managed_external_buffer object construction"]]).
  4984. * [@https://svn.boost.org/trac/boost/ticket/9767 Trac #9767 (['"bootstamp generation causes error in case of corrupt Windows Event Log"])].
  4985. * [@https://svn.boost.org/trac/boost/ticket/9835 Trac #9835 (['"Boost Interprocess fails to compile with Android NDK GCC 4.8, -Werror=unused-variable"])].
  4986. * [@https://svn.boost.org/trac/boost/ticket/9911 Trac #9911 (['"get_tmp_base_dir(...) failure"])].
  4987. * [@https://svn.boost.org/trac/boost/ticket/9946 Trac #9946 (['"ret_ptr uninitialized in init_atomic_func, fini_atomic_func"])].
  4988. * [@https://svn.boost.org/trac/boost/ticket/10011 Trac #10011 (['"segment_manager::find( unique_instance_t* ) fails to compile"])].
  4989. * [@https://svn.boost.org/trac/boost/ticket/10021 Trac #10021 (['"Interprocess and BOOST_USE_WINDOWS_H"])].
  4990. * [@https://svn.boost.org/trac/boost/ticket/10230 Trac #10230 (['"No Sleep in interprocess::winapi"])].
  4991. * [@https://github.com/boostorg/interprocess/pull/2 GitHub Pull #2] (['"Provide support for the Cray C++ compiler. The Cray compiler defines __GNUC__"]]).
  4992. * [@https://github.com/boostorg/interprocess/pull/3 GitHub Pull #3] (['"Fix/mingw interprocess_exception throw in file_wrapper::priv_open_or_create"]]).
  4993. * [*ABI breaking]: [@https://svn.boost.org/trac/boost/ticket/9221 #9221] showed
  4994. that `BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX` option of message queue,
  4995. was completely broken so an ABI break was necessary to have a working implementation.
  4996. * Simplified, refactored and unified (timed_)lock code based on try_lock().
  4997. There were several bugs when handling timeout expirations.
  4998. * Changed the implementation of condition variables' destructors to allow POSIX semantics
  4999. (the condition variable can be destroyed after all waiting threads have been woken up)..
  5000. * Added `BOOST_INTERPROCESS_SHARED_DIR_PATH` option to define the shared directory used to place shared memory objects
  5001. when implemented as memory mapped files.
  5002. * Added support for `BOOST_USE_WINDOWS_H`. When this macro is defined Interprocess does not declare
  5003. used Windows API function and types, includes all needed windows SDK headers and uses types and
  5004. functions declared by the Windows SDK.
  5005. * Added `get_size` to [classref ::boost:interprocess:windows_shared_memory].
  5006. [endsect]
  5007. [section:release_notes_boost_1_55_00 Boost 1.55 Release]
  5008. * Fixed bugs:
  5009. * [@https://svn.boost.org/trac/boost/ticket/7156 #7156] (['"interprocess buffer streams leak memory on construction"]]).
  5010. * [@https://svn.boost.org/trac/boost/ticket/7164 #7164] (['"Two potential bugs with b::int::vector of b::i::weak_ptr"]]).
  5011. * [@https://svn.boost.org/trac/boost/ticket/7860 #7860] (['"smart_ptr's yield_k and spinlock utilities can improve spinlock-based sychronization primitives"]]).
  5012. * [@https://svn.boost.org/trac/boost/ticket/8277 #8277] (['"docs for named_mutex erroneously refer to interprocess_mutex"]]).
  5013. * [@https://svn.boost.org/trac/boost/ticket/8976 #8976] (['"shared_ptr fails to compile if used with a scoped_allocator"]]).
  5014. * [@https://svn.boost.org/trac/boost/ticket/9008 #9008] (['"conditions variables fast enough only when opening a multiprocess browser"]]).
  5015. * [@https://svn.boost.org/trac/boost/ticket/9065 #9065] (['"atomic_cas32 inline assembly wrong on ppc32"]]).
  5016. * [@https://svn.boost.org/trac/boost/ticket/9073 #9073] (['"Conflict names 'realloc'"]]).
  5017. [endsect]
  5018. [section:release_notes_boost_1_54_00 Boost 1.54 Release]
  5019. * Added support for platform-specific flags to mapped_region (ticket #8030)
  5020. * Fixed bugs:
  5021. * [@https://svn.boost.org/trac/boost/ticket/7484 #7484],
  5022. * [@https://svn.boost.org/trac/boost/ticket/7598 #7598],
  5023. * [@https://svn.boost.org/trac/boost/ticket/7682 #7682],
  5024. * [@https://svn.boost.org/trac/boost/ticket/7923 #7923],
  5025. * [@https://svn.boost.org/trac/boost/ticket/7924 #7924],
  5026. * [@https://svn.boost.org/trac/boost/ticket/7928 #7928],
  5027. * [@https://svn.boost.org/trac/boost/ticket/7936 #7936],
  5028. * [@https://svn.boost.org/trac/boost/ticket/8521 #8521],
  5029. * [@https://svn.boost.org/trac/boost/ticket/8595 #8595].
  5030. * [*ABI breaking]: Changed bootstamp function in Windows to use EventLog service start time
  5031. as system bootup time. Previously used `LastBootupTime` from WMI was unstable with
  5032. time synchronization and hibernation and unusable in practice. If you really need
  5033. to obtain pre Boost 1.54 behaviour define `BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME`
  5034. from command line or `detail/workaround.hpp`.
  5035. [endsect]
  5036. [section:release_notes_boost_1_53_00 Boost 1.53 Release]
  5037. * Fixed GCC -Wshadow warnings.
  5038. * Experimental multiple allocation interface improved and changed again. Still unstable.
  5039. * Replaced deprecated BOOST_NO_XXXX with newer BOOST_NO_CXX11_XXX macros.
  5040. * [*ABI breaking]: changed node pool allocators internals for improved efficiency.
  5041. * Fixed bug [@https://svn.boost.org/trac/boost/ticket/7795 #7795].
  5042. [endsect]
  5043. [section:release_notes_boost_1_52_00 Boost 1.52 Release]
  5044. * Added `shrink_by` and `advise` functions in `mapped_region`.
  5045. * [*ABI breaking:] Reimplemented `message_queue` with a circular buffer index (the
  5046. old behavior used an ordered array, leading to excessive copies). This
  5047. should greatly increase performance but breaks ABI. Old behaviour/ABI can be used
  5048. undefining macro `BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX` in `boost/interprocess/detail/workaround.hpp`
  5049. * Improved `message_queue` insertion time avoiding priority search for common cases
  5050. (both array and circular buffer configurations).
  5051. * Implemented `interproces_sharable_mutex` and `interproces_condition_any`.
  5052. * Improved `offset_ptr` performance.
  5053. * Added integer overflow checks.
  5054. [endsect]
  5055. [section:release_notes_boost_1_51_00 Boost 1.51 Release]
  5056. * Synchronous and asynchronous flushing for `mapped_region::flush`.
  5057. * [*Source & ABI breaking]: Removed `get_offset` method from `mapped_region` as
  5058. it has no practical utility and `m_offset` member was not for anything else.
  5059. * [*Source & ABI breaking]: Removed `flush` from `managed_shared_memory`.
  5060. as it is unspecified according to POSIX:
  5061. [@http://pubs.opengroup.org/onlinepubs/009695399/functions/msync.html
  5062. ['"The effect of msync() on a shared memory object or a typed memory object is unspecified"] ].
  5063. * Fixed bug
  5064. [@https://svn.boost.org/trac/boost/ticket/7152 #7152],
  5065. [endsect]
  5066. [section:release_notes_boost_1_50_00 Boost 1.50 Release]
  5067. * Fixed bugs
  5068. [@https://svn.boost.org/trac/boost/ticket/3750 #3750],
  5069. [@https://svn.boost.org/trac/boost/ticket/6727 #6727],
  5070. [@https://svn.boost.org/trac/boost/ticket/6648 #6648],
  5071. * Shared memory in windows has again kernel persistence: kernel bootstamp
  5072. and WMI has received some fixes and optimizations. This causes incompatibility
  5073. with Boost 1.48 and 1.49 but the user can comment `#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME`
  5074. in the windows configuration part to get Boost 1.48 & Boost 1.49 behaviour.
  5075. [endsect]
  5076. [section:release_notes_boost_1_49_00 Boost 1.49 Release]
  5077. * Fixed bugs
  5078. [@https://svn.boost.org/trac/boost/ticket/6531 #6531],
  5079. [@https://svn.boost.org/trac/boost/ticket/6412 #6412],
  5080. [@https://svn.boost.org/trac/boost/ticket/6398 #6398],
  5081. [@https://svn.boost.org/trac/boost/ticket/6340 #6340],
  5082. [@https://svn.boost.org/trac/boost/ticket/6319 #6319],
  5083. [@https://svn.boost.org/trac/boost/ticket/6287 #6287],
  5084. [@https://svn.boost.org/trac/boost/ticket/6265 #6265],
  5085. [@https://svn.boost.org/trac/boost/ticket/6233 #6233],
  5086. [@https://svn.boost.org/trac/boost/ticket/6147 #6147],
  5087. [@https://svn.boost.org/trac/boost/ticket/6134 #6134],
  5088. [@https://svn.boost.org/trac/boost/ticket/6058 #6058],
  5089. [@https://svn.boost.org/trac/boost/ticket/6054 #6054],
  5090. [@https://svn.boost.org/trac/boost/ticket/5772 #5772],
  5091. [@https://svn.boost.org/trac/boost/ticket/5738 #5738],
  5092. [@https://svn.boost.org/trac/boost/ticket/5622 #5622],
  5093. [@https://svn.boost.org/trac/boost/ticket/5552 #5552],
  5094. [@https://svn.boost.org/trac/boost/ticket/5518 #5518],
  5095. [@https://svn.boost.org/trac/boost/ticket/4655 #4655],
  5096. [@https://svn.boost.org/trac/boost/ticket/4452 #4452],
  5097. [@https://svn.boost.org/trac/boost/ticket/4383 #4383],
  5098. [@https://svn.boost.org/trac/boost/ticket/4297 #4297].
  5099. * Fixed timed functions in mutex implementations to fulfill POSIX requirements:
  5100. ['Under no circumstance shall the function fail with a timeout if the mutex can be locked
  5101. immediately. The validity of the abs_timeout parameter need not be checked if the mutex
  5102. can be locked immediately.]
  5103. [endsect]
  5104. [section:release_notes_boost_1_48_00 Boost 1.48 Release]
  5105. * Fixed bugs
  5106. [@https://svn.boost.org/trac/boost/ticket/2796 #2796],
  5107. [@https://svn.boost.org/trac/boost/ticket/4031 #4031],
  5108. [@https://svn.boost.org/trac/boost/ticket/4251 #4251],
  5109. [@https://svn.boost.org/trac/boost/ticket/4452 #4452],
  5110. [@https://svn.boost.org/trac/boost/ticket/4895 #4895],
  5111. [@https://svn.boost.org/trac/boost/ticket/5077 #5077],
  5112. [@https://svn.boost.org/trac/boost/ticket/5120 #5120],
  5113. [@https://svn.boost.org/trac/boost/ticket/5123 #5123],
  5114. [@https://svn.boost.org/trac/boost/ticket/5230 #5230],
  5115. [@https://svn.boost.org/trac/boost/ticket/5197 #5197],
  5116. [@https://svn.boost.org/trac/boost/ticket/5287 #5287],
  5117. [@https://svn.boost.org/trac/boost/ticket/5294 #5294],
  5118. [@https://svn.boost.org/trac/boost/ticket/5306 #5306],
  5119. [@https://svn.boost.org/trac/boost/ticket/5308 #5308],
  5120. [@https://svn.boost.org/trac/boost/ticket/5392 #5392],
  5121. [@https://svn.boost.org/trac/boost/ticket/5409 #5409],
  5122. * Added support to customize offset_ptr and allow
  5123. creating custom managed segments that might be shared between
  5124. 32 and 64 bit processes.
  5125. * Shared memory in windows has again filesystem lifetime: kernel bootstamp
  5126. and WMI use to get a reliable timestamp was causing a lot of trouble.
  5127. [endsect]
  5128. [section:release_notes_boost_1_46_00 Boost 1.46 Release]
  5129. * Fixed bugs
  5130. [@https://svn.boost.org/trac/boost/ticket/4557 #4557],
  5131. [@https://svn.boost.org/trac/boost/ticket/4979 #4979],
  5132. [@https://svn.boost.org/trac/boost/ticket/4907 #4907],
  5133. [@https://svn.boost.org/trac/boost/ticket/4895 #4895].
  5134. [endsect]
  5135. [section:release_notes_boost_1_45_00 Boost 1.45 Release]
  5136. * Fixed bugs
  5137. [@https://svn.boost.org/trac/boost/ticket/1080 #1080],
  5138. [@https://svn.boost.org/trac/boost/ticket/3284 #3284],
  5139. [@https://svn.boost.org/trac/boost/ticket/3439 #3439],
  5140. [@https://svn.boost.org/trac/boost/ticket/3448 #3448],
  5141. [@https://svn.boost.org/trac/boost/ticket/3582 #3582],
  5142. [@https://svn.boost.org/trac/boost/ticket/3682 #3682],
  5143. [@https://svn.boost.org/trac/boost/ticket/3829 #3829],
  5144. [@https://svn.boost.org/trac/boost/ticket/3846 #3846],
  5145. [@https://svn.boost.org/trac/boost/ticket/3914 #3914],
  5146. [@https://svn.boost.org/trac/boost/ticket/3947 #3947],
  5147. [@https://svn.boost.org/trac/boost/ticket/3950 #3950],
  5148. [@https://svn.boost.org/trac/boost/ticket/3951 #3951],
  5149. [@https://svn.boost.org/trac/boost/ticket/3985 #3985],
  5150. [@https://svn.boost.org/trac/boost/ticket/4010 #4010],
  5151. [@https://svn.boost.org/trac/boost/ticket/4417 #4417],
  5152. [@https://svn.boost.org/trac/boost/ticket/4019 #4019],
  5153. [@https://svn.boost.org/trac/boost/ticket/4039 #4039],
  5154. [@https://svn.boost.org/trac/boost/ticket/4218 #4218],
  5155. [@https://svn.boost.org/trac/boost/ticket/4230 #4230],
  5156. [@https://svn.boost.org/trac/boost/ticket/4250 #4250],
  5157. [@https://svn.boost.org/trac/boost/ticket/4297 #4297],
  5158. [@https://svn.boost.org/trac/boost/ticket/4350 #4350],
  5159. [@https://svn.boost.org/trac/boost/ticket/4352 #4352],
  5160. [@https://svn.boost.org/trac/boost/ticket/4426 #4426],
  5161. [@https://svn.boost.org/trac/boost/ticket/4516 #4516],
  5162. [@https://svn.boost.org/trac/boost/ticket/4524 #4524],
  5163. [@https://svn.boost.org/trac/boost/ticket/4557 #4557],
  5164. [@https://svn.boost.org/trac/boost/ticket/4606 #4606],
  5165. [@https://svn.boost.org/trac/boost/ticket/4685 #4685],
  5166. [@https://svn.boost.org/trac/boost/ticket/4694 #4694].
  5167. * Added support for standard rvalue reference move semantics
  5168. (tested on GCC 4.5 and VC10).
  5169. * Permissions can be detailed for interprocess named resources.
  5170. * `mapped_region::flush` initiates disk flushing but does not guarantee it's completed
  5171. when returns, since it is not portable.
  5172. * FreeBSD and MacOS now use posix semaphores to implement named semaphores and mutex.
  5173. [endsect]
  5174. [section:release_notes_boost_1_41_00 Boost 1.41 Release]
  5175. * Support for POSIX shared memory in Mac OS.
  5176. * [*ABI breaking]: Generic `semaphore` and `named_semaphore` now implemented more efficiently with atomic operations.
  5177. * More robust file opening in Windows platforms with active Anti-virus software.
  5178. [endsect]
  5179. [section:release_notes_boost_1_40_00 Boost 1.40 Release]
  5180. * Windows shared memory is created in Shared Documents folder so that it can be shared
  5181. between services and processes
  5182. * Fixed bugs
  5183. [@https://svn.boost.org/trac/boost/ticket/2967 #2967],
  5184. [@https://svn.boost.org/trac/boost/ticket/2973 #2973],
  5185. [@https://svn.boost.org/trac/boost/ticket/2992 #2992],
  5186. [@https://svn.boost.org/trac/boost/ticket/3138 #3138],
  5187. [@https://svn.boost.org/trac/boost/ticket/3166 #3166],
  5188. [@https://svn.boost.org/trac/boost/ticket/3205 #3205].
  5189. [endsect]
  5190. [section:release_notes_boost_1_39_00 Boost 1.39 Release]
  5191. * Added experimental `stable_vector` container.
  5192. * `shared_memory_object::remove` has now POSIX `unlink` semantics and
  5193. `file_mapping::remove` was added to obtain POSIX `unlink` semantics with mapped files.
  5194. * Shared memory in windows has now kernel lifetime instead of filesystem lifetime: shared
  5195. memory will disappear when the system reboots.
  5196. * Updated move semantics.
  5197. * Fixed bugs
  5198. [@https://svn.boost.org/trac/boost/ticket/2722 #2722],
  5199. [@https://svn.boost.org/trac/boost/ticket/2729 #2729],
  5200. [@https://svn.boost.org/trac/boost/ticket/2766 #2766],
  5201. [@https://svn.boost.org/trac/boost/ticket/1390 #1390],
  5202. [@https://svn.boost.org/trac/boost/ticket/2589 #2589],
  5203. [endsect]
  5204. [section:release_notes_boost_1_38_00 Boost 1.38 Release]
  5205. * Updated documentation to show rvalue-references funcions instead of emulation functions.
  5206. * More non-copyable classes are now movable.
  5207. * Move-constructor and assignments now leave moved object in default-constructed state
  5208. instead of just swapping contents.
  5209. * Several bugfixes (
  5210. [@https://svn.boost.org/trac/boost/ticket/2391 #2391],
  5211. [@https://svn.boost.org/trac/boost/ticket/2431 #2431],
  5212. [@https://svn.boost.org/trac/boost/ticket/1390 #1390],
  5213. [@https://svn.boost.org/trac/boost/ticket/2570 #2570],
  5214. [@https://svn.boost.org/trac/boost/ticket/2528 #2528].
  5215. [endsect]
  5216. [section:release_notes_boost_1_37_00 Boost 1.37 Release]
  5217. * Containers can be used now in recursive types.
  5218. * Added `BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION` macro option to force the use
  5219. of generic emulation code for process-shared synchronization primitives instead of
  5220. native POSIX functions.
  5221. * Added placement insertion members to containers
  5222. * `boost::posix_time::pos_inf` value is now handled portably for timed functions.
  5223. * Update some function parameters from `iterator` to `const_iterator` in containers
  5224. to keep up with the draft of the next standard.
  5225. * Documentation fixes.
  5226. [endsect]
  5227. [section:release_notes_boost_1_36_00 Boost 1.36 Release]
  5228. * Added anonymous shared memory for UNIX systems.
  5229. * Fixed erroneous `void` return types from `flat_map::erase()` functions.
  5230. * Fixed missing move semantics on managed memory classes.
  5231. * Added copy_on_write and open_read_only options for shared memory and mapped file managed classes.
  5232. * [*ABI breaking]: Added to `mapped_region` the mode used to create it.
  5233. * Corrected instantiation errors in void allocators.
  5234. * `shared_ptr` is movable and supports aliasing.
  5235. [endsect]
  5236. [section:release_notes_boost_1_35_00 Boost 1.35 Release]
  5237. * Added auxiliary utilities to ease the definition and construction of
  5238. [classref boost::interprocess::shared_ptr shared_ptr],
  5239. [classref boost::interprocess::weak_ptr weak_ptr] and
  5240. `unique_ptr`. Added explanations
  5241. and examples of these smart pointers in the documentation.
  5242. * Optimized vector:
  5243. * 1) Now works with raw pointers as much as possible when
  5244. using allocators defining `pointer` as an smart pointer. This increases
  5245. performance and improves compilation times.
  5246. * 2) A bit of metaprogramming
  5247. to avoid using move_iterator when the type has trivial copy constructor
  5248. or assignment and improve performance.
  5249. * 3) Changed custom algorithms
  5250. with standard ones to take advantage of optimized standard algorithms.
  5251. * 4) Removed unused code.
  5252. * [*ABI breaking]: Containers don't derive from allocators, to avoid problems with allocators
  5253. that might define virtual functions with the same names as container
  5254. member functions. That would convert container functions in virtual functions
  5255. and might disallow some of them if the returned type does not lead to a covariant return.
  5256. Allocators are now stored as base classes of internal structs.
  5257. * Implemented [classref boost::interprocess::named_mutex named_mutex] and
  5258. [classref boost::interprocess::named_semaphore named_semaphore] with POSIX
  5259. named semaphores in systems supporting that option.
  5260. [classref boost::interprocess::named_condition named_condition] has been
  5261. accordingly changed to support interoperability with
  5262. [classref boost::interprocess::named_mutex named_mutex].
  5263. * Reduced template bloat for node and adaptive allocators extracting node
  5264. implementation to a class that only depends on the memory algorithm, instead of
  5265. the segment manager + node size + node number...
  5266. * Fixed bug in `mapped_region` in UNIX when mapping address was provided but
  5267. the region was mapped in another address.
  5268. * Added `aligned_allocate` and `allocate_many` functions to managed memory segments.
  5269. * Improved documentation about managed memory segments.
  5270. * [*Boost.Interprocess] containers are now documented in the Reference section.
  5271. * Correction of typos and documentation errors.
  5272. * Added `get_instance_name`, `get_instance_length` and `get_instance_type` functions
  5273. to managed memory segments.
  5274. * Corrected suboptimal buffer expansion bug in `rbtree_best_fit`.
  5275. * Added iteration of named and unique objects in a segment manager.
  5276. * Fixed leak in [classref boost::interprocess::vector vector].
  5277. * Added support for Solaris.
  5278. * Optimized [classref boost::interprocess::segment_manager segment_manager]
  5279. to avoid code bloat associated with templated instantiations.
  5280. * Fixed bug for UNIX: No slash ('/') was being added as the first character
  5281. for shared memory names, leading to errors in some UNIX systems.
  5282. * Fixed bug in VC-8.0: Broken function inlining in core offset_ptr functions.
  5283. * Code examples changed to use new BoostBook code import features.
  5284. * Added aligned memory allocation function to memory algorithms.
  5285. * Fixed bug in `deque::clear()` and `deque::erase()`, they were declared private.
  5286. * Fixed bug in `deque::erase()`. Thanks to Steve LoBasso.
  5287. * Fixed bug in `atomic_dec32()`. Thanks to Glenn Schrader.
  5288. * Improved (multi)map/(multi)set constructors taking iterators. Now those have
  5289. linear time if the iterator range is already sorted.
  5290. * [*ABI breaking]: (multi)map/(multi)set now reduce their node size. The color
  5291. bit is embedded in the parent pointer. Now, the size of a node is the size of
  5292. 3 pointers in most systems. This optimization is activated for raw and `offset_ptr`
  5293. pointers.
  5294. * (multi)map/(multi)set now reuse memory from old nodes in the assignment operator.
  5295. * [*ABI breaking]: Implemented node-containers based on intrusive containers.
  5296. This saves code size, since many instantiations share the same algorithms.
  5297. * Corrected code to be compilable with Visual C++ 8.0.
  5298. * Added function to zero free memory in memory algorithms and the segment manager.
  5299. This function is useful for security reasons and to improve compression ratios
  5300. for files created with `managed_mapped_file`.
  5301. * Added support for intrusive index types in managed memory segments.
  5302. Intrusive indexes save extra memory allocations to allocate the index
  5303. since with just one
  5304. allocation, we allocate room for the value, the name and the hook to insert
  5305. the object in the index.
  5306. * Created new index type: [*iset_index]. It's an index based on
  5307. an intrusive set (rb-tree).
  5308. * Created new index type: [*iunordered_set_index]. It's an index
  5309. based on a pseudo-intrusive unordered set (hash table).
  5310. * [*ABI breaking]: The intrusive index [*iset_index] is now the default
  5311. index type.
  5312. * Optimized vector to take advantage of `boost::has_trivial_destructor`.
  5313. This optimization avoids calling destructors of elements that have a trivial destructor.
  5314. * Optimized vector to take advantage of `has_trivial_destructor_after_move` trait.
  5315. This optimization avoids calling destructors of elements that have a trivial destructor
  5316. if the element has been moved (which is the case of many movable types). This trick
  5317. was provided by Howard Hinnant.
  5318. * Added security check to avoid integer overflow bug in allocators and
  5319. named construction functions.
  5320. * Added alignment checks to forward and backwards expansion functions.
  5321. * Fixed bug in atomic functions for PPC.
  5322. * Fixed race-condition error when creating and opening a managed segment.
  5323. * Added adaptive pools.
  5324. * [*Source breaking]: Changed node allocators' template parameter order
  5325. to make them easier to use.
  5326. * Added support for native windows shared memory.
  5327. * Added more tests.
  5328. * Corrected the presence of private functions in the reference section.
  5329. * Added function (`deallocate_free_chunks()`) to manually deallocate completely free
  5330. chunks from node allocators.
  5331. * Implemented N1780 proposal to LWG issue 233: ['Insertion hints in associative containers]
  5332. in interprocess [classref boost::interprocess::multiset multiset] and
  5333. [classref boost::interprocess::multimap multimap] classes.
  5334. * [*Source breaking]: A shared memory object is now used including
  5335. `shared_memory_object.hpp` header instead of `shared memory.hpp`.
  5336. * [*ABI breaking]: Changed global mutex when initializing managed shared memory
  5337. and memory mapped files. This change tries to minimize deadlocks.
  5338. * [*Source breaking]: Changed shared memory, memory mapped files and mapped region's
  5339. open mode to a single `mode_t` type.
  5340. * Added extra WIN32_LEAN_AND_MEAN before including DateTime headers to avoid socket
  5341. redefinition errors when using Interprocess and Asio in windows.
  5342. * [*ABI breaking]: `mapped_region` constructor no longer requires classes
  5343. derived from memory_mappable, but classes must fulfill the MemoryMappable concept.
  5344. * Added in-place reallocation capabilities to basic_string.
  5345. * [*ABI breaking]: Reimplemented and optimized small string optimization. The narrow
  5346. string class has zero byte overhead with an internal 11 byte buffer in 32 systems!
  5347. * Added move semantics to containers. Improves
  5348. performance when using containers of containers.
  5349. * [*ABI breaking]: End nodes of node containers (list, slist, map/set) are now
  5350. embedded in the containers instead of allocated using the allocator. This
  5351. allows no-throw move-constructors and improves performance.
  5352. * [*ABI breaking]: [*slist] and [*list] containers now have constant-time
  5353. ['size()] function. The size of the container is added as a member.
  5354. [endsect]
  5355. [endsect]
  5356. [section:books_and_links Books and interesting links]
  5357. Some useful references about the C++ programming language, C++ internals,
  5358. shared memory, allocators and containers used to design [*Boost.Interprocess].
  5359. [section:references_books Books]
  5360. * Great book about multithreading, and POSIX: [*['"Programming with Posix Threads"]],
  5361. [*David R. Butenhof]
  5362. * The UNIX inter-process bible: [*['"UNIX Network Programming, Volume 2: Interprocess Communications"]],
  5363. [*W. Richard Stevens]
  5364. * Current STL allocator issues: [*['"Effective STL"]], [*Scott Meyers]
  5365. * My C++ bible: [*['"Thinking in C++, Volume 1 & 2"]], [*Bruce Eckel and Chuck Allison]
  5366. * The book every C++ programmer should read: [*['"Inside the C++ Object Model"]], [*Stanley B. Lippman]
  5367. * A must-read: [*['"ISO/IEC TR 18015: Technical Report on C++ Performance"]], [*ISO WG21-SC22 members.]
  5368. [endsect]
  5369. [section:references_links Links]
  5370. * A framework to put the STL in shared memory: [@http://allocator.sourceforge.net/ ['"A C++ Standard Allocator for the Standard Template Library"] ].
  5371. * Instantiating C++ objects in shared memory: [@http://www.cs.ubc.ca/local/reading/proceedings/cascon94/htm/english/abs/hon.htm ['"Using objects in shared memory for C++ application"] ].
  5372. * A shared memory allocator and relative pointer: [@http://home.earthlink.net/~joshwalker1/writing/SharedMemory.html ['"Taming Shared Memory"] ].
  5373. [endsect]
  5374. [endsect]
  5375. [section:future_improvements Future improvements...]
  5376. There are some Interprocess features that I would like to implement and some
  5377. [*Boost.Interprocess] code that can be much better. Let's see some ideas:
  5378. [section:win32_sync Win32 synchronization is too basic]
  5379. Win32 version of shared mutexes and shared conditions are based on "spin and wait"
  5380. atomic instructions. This leads to poor performance and does not manage any issues
  5381. like priority inversions. We would need very serious help from threading experts on
  5382. this. And I'm not sure that this can be achieved in user-level software. Posix based
  5383. implementations use PTHREAD_PROCESS_SHARED attribute to place mutexes in shared memory,
  5384. so there are no such problems. I'm not aware of any implementation that simulates
  5385. PTHREAD_PROCESS_SHARED attribute for Win32. We should be able to construct these
  5386. primitives in memory mapped files, so that we can get filesystem persistence just like
  5387. with POSIX primitives.
  5388. [endsect]
  5389. [section:future_objectnames Use of wide character names on Boost.Interprocess basic resources]
  5390. Currently Interprocess only allows *char* based names for basic named
  5391. objects. However, several operating systems use *wchar_t* names for resources
  5392. (mapped files, for example).
  5393. In the future Interprocess should try to present a portable narrow/wide char interface.
  5394. To do this, it would be useful to have a boost wstring <-> string conversion
  5395. utilities to translate resource names (escaping needed characters
  5396. that can conflict with OS names) in a portable way. It would be interesting also
  5397. the use of [*boost::filesystem] paths to avoid operating system specific issues.
  5398. [endsect]
  5399. [section:future_security Security attributes]
  5400. [*Boost.Interprocess] does not define security attributes for shared memory and
  5401. synchronization objects. Standard C++ also ignores security attributes with files
  5402. so adding security attributes would require some serious work.
  5403. [endsect]
  5404. [section:future_ipc Future inter-process communications]
  5405. [*Boost.Interprocess] offers a process-shared message queue based on
  5406. [*Boost.Interprocess] primitives like mutexes and conditions. I would want to
  5407. develop more mechanisms, like stream-oriented named fifo so that we can use it
  5408. with a iostream-interface wrapper (we can imitate Unix pipes).
  5409. C++ needs more complex mechanisms and it would be nice to have a stream and
  5410. datagram oriented PF_UNIX-like mechanism in C++. And for very fast inter-process
  5411. remote calls Solaris doors is an interesting alternative to implement for C++.
  5412. But the work to implement PF_UNIX-like sockets and doors would be huge
  5413. (and it might be difficult in a user-level library). Any network expert volunteer?
  5414. [endsect]
  5415. [endsect]
  5416. [endsect]
  5417. [section:indexes_reference Indexes and Reference]
  5418. [section:index Indexes]
  5419. [include auto_index_helpers.qbk]
  5420. [named_index class_name Class Index]
  5421. [named_index typedef_name Typedef Index]
  5422. [named_index function_name Function Index]
  5423. [/named_index macro_name Macro Index]
  5424. [/index]
  5425. [endsect]
  5426. [xinclude autodoc.xml]
  5427. [endsect]