内部可变性允许通过共享引用访问的对象改变部分内部状态,例如缓存、计数和同步队列。它不取消“不能同时存在冲突访问”的要求,而是由封装选择另一种可以证明安全的访问协议。
共享引用的一般不可变约束在 UnsafeCell 所包裹的部分有例外。但 UnsafeCell 本身不提供锁,不允许任意创建相互别名的 &mut,也不允许数据竞争。UnsafeCell
Cell<T> 移出、替换或复制值 RefCell<T> 动态借用 guard Mutex<T> 互斥锁 guard 不发放普通共享借用 get 要求 Copy,replace 不要求 读者或独占写者 冲突返回错误或 panic 一次一个持锁者 竞争等待或 try_lock 失败 共享入口不同,内部访问协议也不同 UnsafeCell 是底层原语;安全接口还必须自行维护别名与同步规则。
Cell 并非 Copy 专用
Cell::get 要求 T: Copy,因为它返回内部值的副本。set 和 replace 可以用于非 Copy 类型;replace 把旧值移出来并放入新值,不需要暴露内部借用。take 在 T: Default 时用默认值替换,into_inner 消费 Cell 并取出 T。Cell
use std:: cell:: Cell;
fn main ( ) {
let name = Cell:: new( String :: from( " before" ) ) ;
let old = name.replace ( String :: from( " after" ) ) ;
assert_eq! ( old, " before" ) ;
assert_eq! ( name.take ( ) , " after" ) ;
assert_eq! ( name.into_inner ( ) , " " ) ;
}
因此 Cell 是合法而有用的,只是不能调用 get。它没有 RefCell 的动态借用计数,不等于操作绝对零成本:替换 String 仍可能涉及其资源管理。
“Cell 永远不返回引用”也太绝对。持有 &mut Cell 时,get_mut 可以返回 &mut T;这时独占借用已经由编译器保证,无需额外运行时协议。
单线程也需要考虑观察到中间状态
用 Cell::take 临时取出一个 Vec,处理完再 set 回去,看起来避开了借用 guard;但处理中若调用可重入的外部代码,其他入口可能看到默认空 Vec。如果处理中 panic,取出的值可能直接析构,原 Cell 则继续为空。Cell 保证这种访问在内存层面安全,不保证“取出—处理—放回”具有事务语义。
因此 Cell 更适合本来就允许整体替换、且中间状态有明确意义的数据。若必须临时借用内部结构,RefCell 通常能更直接表达访问期间的排他性;若操作可能失败,还应在提交前计算新值,或设计可恢复的状态转换。
RefCell 用 guard 记录动态借用
borrow 返回 Ref,borrow_mut 返回 RefMut。通常允许多个共享借用,或一个独占借用。guard 被释放后,对应借用才结束,不能根据“最后一次读值已经过去”就假定 guard 自动失效。
use std:: cell:: RefCell;
fn main ( ) {
let values = RefCell:: new( vec! [ 1 , 2 ] ) ;
let reading = values.borrow ( ) ;
assert! ( values.try_borrow_mut ( ) .is_err ( ) ) ;
assert_eq! ( reading.len ( ) , 2 ) ;
drop ( reading) ;
values.borrow_mut ( ) .push ( 3 ) ;
assert_eq! ( & * values.borrow ( ) , & [ 1 , 2 , 3 ] ) ;
}
borrow/borrow_mut 在冲突时 panic;try_borrow/try_borrow_mut 把冲突作为 Result 返回,并不会等待另一个借用结束。容易遗漏的冲突来源包括回调重入,以及在整个 match 或其他较长表达式期间存活的临时 guard。RefCell
RefCell 在 T: Send 时可以整体转移到另一线程,但它不 Sync。Rc<RefCell> 是单线程共享所有权加动态借用,并不是可跨线程共享的组合。
从内部字段返回引用,要把 guard 一起返回
use std:: cell:: { Ref, RefCell} ;
struct Profile {
fields : RefCell< ( String, u32 ) > ,
}
impl Profile {
fn name ( & self ) -> Ref< '_ , str > {
Ref:: map( self .fields.borrow ( ) , | fields | fields.0. as_str ( ) )
}
}
fn main ( ) {
let profile = Profile { fields: RefCell:: new( ( " Li" .into ( ) , 7 ) ) } ;
let name = profile.name ( ) ;
assert_eq! ( & * name, " Li" ) ;
assert! ( profile.fields.try_borrow_mut ( ) .is_err ( ) ) ;
drop ( name) ;
profile.fields.borrow_mut ( ) .0. push ( ' !' ) ;
assert_eq! ( & * profile.name ( ) , " Li!" ) ;
}
不能在函数中创建临时 Ref,再把其中的 &str 当作无 guard 的普通引用返回;函数结束时动态借用凭证会消失。Ref::map 把 guard 的可见范围投影到字段,同时保留整个 RefCell 的共享借用状态。即使只读取 name,也不能同时通过同一个 RefCell 借出独占的数字字段;映射没有把一个 RefCell 自动拆成两个独立借用单元。Ref::map
在调用外部代码前结束动态借用
use std:: cell:: RefCell;
fn notify ( queue : & RefCell< Vec< u32 > > , callback : impl FnOnce( usize ) ) {
let count = {
let reading = queue.borrow ( ) ;
reading.len ( )
} ;
callback ( count) ;
}
fn main ( ) {
let queue = RefCell:: new( vec! [ 1 , 2 ] ) ;
notify ( & queue, | count | {
assert_eq! ( count, 2 ) ;
queue.borrow_mut ( ) .push ( 3 ) ;
} ) ;
assert_eq! ( & * queue.borrow ( ) , & [ 1 , 2 , 3 ] ) ;
}
这里把需要的标量先取出,释放 guard,再调用 callback,因此回调可以修改队列。如果 callback 在 reading 仍存活时调用 borrow_mut,会发生借用冲突。代价是 count 仅代表取值时的状态,回调执行后不再保证它等于队列当前长度;如果业务必须保持状态稳定,就应限制回调能做什么,或改成提交事件后由外层处理。
不要依赖“单线程所以没有竞争”来忽略重入。单线程不会同时执行两条机器指令流,但外部回调可以在原操作尚未完成时重新进入同一个对象。
最后读取之后,guard 还在吗?
这里刻意把“读取”与“释放 guard”做成不同操作。申请 Ref 后读取一次,再申请 RefMut,仍会失败;只有释放所有共享 guard,才满足独占借用条件。这解释了为什么普通引用的最后使用分析不能直接套在 Ref 或 MutexGuard 上。
正在呈现知识画面 重新加载
最后读取之后,guard 还在吗? 动态借用由 guard 的生命维护;最后一次读取不是释放 guard。
{"id":"rust-refcell-guards","title":"最后读取之后,guard 还在吗?","summary":"动态借用由 guard 的生命维护;最后一次读取不是释放 guard。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><div class=\"actions\"><button id=\"read\" data-i18n=\"read\"></button><button id=\"write\" data-i18n=\"write\"></button><button id=\"last\" data-i18n=\"last\"></button><button id=\"dropRead\" data-i18n=\"dropRead\"></button><button id=\"dropWrite\" data-i18n=\"dropWrite\"></button><button id=\"reset\" data-i18n=\"reset\"></button></div><section class=\"panel\"><h3 data-i18n=\"guards\"></h3><div id=\"guards\"></div></section><section class=\"panel\"><h3 data-i18n=\"state\"></h3><div id=\"state\"></div></section><div class=\"copy\"><p id=\"explanation\" role=\"status\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"initial\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"ok\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"bad\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"used\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"dropped\"></p></div><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:550;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:550 20px ui-monospace,monospace}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:ui-monospace,monospace;font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px ui-monospace,monospace;background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n/* Action labels must remain readable across locales and narrow embeds. */\n.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n.actions button{overflow-wrap:anywhere;white-space:normal;min-height:58px;padding:8px}\nbutton{overflow-wrap:anywhere}\n@media(min-width:640px){.actions{grid-template-columns:repeat(3,minmax(0,1fr))}}\n\n.metrics span{overflow-wrap:anywhere}\n.panel{border:1px solid var(--rule);border-radius:9px;padding:12px;margin:14px 0;min-width:0}.panel h3{font-size:13px;margin:0 0 10px;color:var(--muted)}.source{font:13px/1.8 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.source mark{background:var(--accent-soft);color:var(--ink);border-bottom:2px solid var(--accent)}.source .fault{background:var(--second-soft);border-color:var(--second)}.diagram{display:block;width:100%;height:auto;max-height:320px;margin:14px 0;overflow:visible}.diagram text{fill:var(--ink);font:12px ui-monospace,monospace}.diagram .edge{stroke:var(--muted);stroke-width:1.5;fill:none}.diagram .edge.on{stroke:var(--accent);stroke-width:3}.diagram .node{fill:var(--surface);stroke:var(--rule);stroke-width:1.5}.diagram .node.on{fill:var(--accent-soft);stroke:var(--accent)}.diagram .node.gold{fill:var(--second-soft);stroke:var(--second)}.log{font:12px/1.8 ui-monospace,monospace;white-space:pre-line;overflow-wrap:anywhere;min-height:7.2em}.table{display:grid;gap:5px;margin:14px 0}.table .tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.table .tr>*{padding:8px 5px;background:var(--surface);border-radius:4px;min-width:0;overflow-wrap:anywhere;font-size:12px}.table .tr .on{background:var(--accent-soft)}.table .tr .gold{background:var(--second-soft)}.choices button{min-height:44px}.metrics strong{min-height:1.6em}.code-line{display:block}.code-line.on{background:var(--accent-soft);border-left:2px solid var(--accent);padding-left:6px}.status-badge{font-size:12px;color:var(--accent)}.tile-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}.tile-grid .cell{min-height:40px}.actions button{min-height:48px}.form-field{display:grid;gap:8px;margin:14px 0;font-size:13px}.form-field input{width:100%;font-family:ui-monospace,monospace}.metrics.three{grid-template-columns:repeat(3,minmax(0,1fr))}.formula{min-height:3.2em}.presets{flex-wrap:wrap}.presets button{flex-basis:25%;min-height:44px}\n\n.budget{display:flex;height:28px;margin:16px 0;background:var(--surface);border-radius:5px;overflow:hidden}.budget i{display:block;background:var(--accent);transition:width .2s}.budget i.gold{background:var(--second)}.intervals{margin:16px 0}.interval{position:relative;height:36px;background:var(--surface);margin:6px 0;border-radius:4px;overflow:hidden}.interval i{position:absolute;height:100%;background:var(--accent-soft);border-left:2px solid var(--accent)}.interval i.gold{background:var(--second-soft);border-color:var(--second)}.interval span{position:relative;z-index:1;font:12px/36px ui-monospace,monospace;padding-left:7px}.table .tr>*{min-height:4.8em}.formula{white-space:pre-line;min-height:7.2em}.actions:has(>button:only-child){grid-template-columns:1fr}.metrics strong{min-height:3.2em}.rangegrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:3px;margin:14px 0}.rangegrid .cell{min-height:30px;padding:3px 1px;font-size:10px}.message{min-height:7.2em;white-space:pre-line;font:13px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}\n/* Allow CJK hanging punctuation without overflowing a metric's border box. */\n.metrics>div{padding-right:4px}.metrics span{line-break:anywhere}\n\n.chart-wrap{margin:18px 0}.chart-label{font-size:12px;color:var(--muted);min-height:3.2em}.curve{display:block;width:100%;height:auto;max-height:320px;overflow:visible}.curve text{font:11px ui-monospace,monospace;fill:var(--muted)}.gridline{stroke:var(--rule);stroke-width:1}.metrics strong{font-size:20px;min-height:3.2em}.formula{font:12px/1.8 ui-monospace,monospace;min-height:9em}.readout{min-height:8em}.presets button{flex-basis:30%}.scope p{overflow-wrap:anywhere} .unit-note{font-size:12px;color:var(--muted);margin:10px 0}\n\n.metrics span{word-break:break-all;line-break:strict}.metrics>div{padding-right:6px}\n\n.cell{min-height:72px}.metrics strong{min-height:3.6em}\n\n#guards{min-height:110px}#state{min-height:3em;font:16px ui-monospace,monospace}.track{flex-wrap:wrap}.cell{flex-basis:20%}","js":"const $=s=>document.querySelector(s);const set=(id,v)=>$('#'+id).textContent=v;const t=k=>viz.t(k);function cells(id,values){$('#'+id).replaceChildren(...values.map(v=>{const e=document.createElement('div');e.className='cell '+(v.cls||'');e.textContent=v.text;e.title=v.title||v.text;return e;}));}function pressed(mode){document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}const esc=s=>String(s).replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]));const fmt=s=>'{'+[...s].sort().join(', ')+'}';function graph(id,nodes,edges){const el=$('#'+id);el.setAttribute('viewBox','0 0 360 200');el.innerHTML='<defs><marker id=\"arrow-'+id+'\" viewBox=\"0 0 10 10\" refX=\"8\" refY=\"5\" markerWidth=\"5\" markerHeight=\"5\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"var(--muted)\"/></marker></defs>'+edges.map(e=>{const a=nodes[e[0]],b=nodes[e[1]],dx=b.x-a.x,dy=b.y-a.y,d=Math.hypot(dx,dy)||1;if(edges.some(r=>r[0]===e[1]&&r[1]===e[0])){const nx=-dy/d,ny=dx/d;return '<path class=\"edge '+(e[2]?'on':'')+'\" d=\"M '+(a.x+dx/d*22+nx*12)+' '+(a.y+dy/d*22+ny*12)+' Q '+((a.x+b.x)/2+nx*38)+' '+((a.y+b.y)/2+ny*38)+' '+(b.x-dx/d*25+nx*12)+' '+(b.y-dy/d*25+ny*12)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}return '<line class=\"edge '+(e[2]?'on':'')+'\" x1=\"'+(a.x+dx/d*25)+'\" y1=\"'+(a.y+dy/d*25)+'\" x2=\"'+(b.x-dx/d*28)+'\" y2=\"'+(b.y-dy/d*28)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}).join('')+nodes.map(n=>'<g><circle class=\"node '+(n.cls||'')+'\" cx=\"'+n.x+'\" cy=\"'+n.y+'\" r=\"25\"/><text x=\"'+n.x+'\" y=\"'+(n.y+4)+'\" text-anchor=\"middle\">'+esc(n.name)+'</text>'+(n.sub?'<text x=\"'+n.x+'\" y=\"'+(n.y+43)+'\" text-anchor=\"middle\">'+esc(n.sub)+'</text>':'')+'</g>').join('');}function table(id,rows){$('#'+id).classList.add('table');$('#'+id).replaceChildren(...rows.map(r=>{const row=document.createElement('div');row.className='tr';row.style.gridTemplateColumns='repeat('+r.length+',minmax(0,1fr))';r.forEach(x=>{const c=document.createElement('div');if(typeof x==='object'){c.textContent=x.text;c.className=x.cls||'';}else c.textContent=x;row.append(c)});return row;}));}function band(id,parts,total){$('#'+id).replaceChildren(...parts.map((p,i)=>{const e=document.createElement('i');e.style.width=(100*p.value/total)+'%';e.className=i%2?'gold':'on';e.title=p.name+': '+p.value;return e}));}function intervals(id,items,total){$('#'+id).replaceChildren(...items.map(p=>{const row=document.createElement('div');row.className='interval';const bar=document.createElement('i');bar.style.left=(100*p.start/total)+'%';bar.style.width=(100*(p.end-p.start)/total)+'%';bar.className=p.cls||'';const label=document.createElement('span');label.textContent=p.label;row.append(bar,label);return row;}));}function plot(id,series,xr,yr,opts={}){const e=$('#'+id),X=x=>42+(x-xr[0])/(xr[1]-xr[0])*298,Y=y=>175-(y-yr[0])/(yr[1]-yr[0])*148;let out='<defs><clipPath id=\"clip-'+id+'\"><rect x=\"42\" y=\"27\" width=\"298\" height=\"148\"/></clipPath></defs>';for(let i=0;i<3;i++){let x=xr[0]+i*(xr[1]-xr[0])/2,y=yr[0]+i*(yr[1]-yr[0])/2;out+='<path class=\"gridline\" d=\"M '+X(x)+' 27V175M42 '+Y(y)+'H340\"/><text x=\"'+X(x)+'\" y=\"194\" text-anchor=\"middle\">'+esc(opts.xfmt?opts.xfmt(x):Number(x.toFixed(2)))+'</text><text x=\"36\" y=\"'+(Y(y)+4)+'\" text-anchor=\"end\">'+esc(opts.yfmt?opts.yfmt(y):Number(y.toFixed(2)))+'</text>';}out+='<g clip-path=\"url(#clip-'+id+')\">';for(const s of series){out+='<path fill=\"none\" stroke=\"'+(s.color||'var(--accent)')+'\" stroke-width=\"2.5\" '+(s.dash?'stroke-dasharray=\"5 4\"':'')+' d=\"'+s.pts.map((p,i)=>(i?'L':'M')+X(p[0]).toFixed(2)+','+Y(p[1]).toFixed(2)).join(' ')+'\"/>';}for(const p of opts.points||[])out+='<circle cx=\"'+X(p[0])+'\" cy=\"'+Y(p[1])+'\" r=\"4\" fill=\"var(--second)\" stroke=\"var(--paper)\" stroke-width=\"1.5\"/>';if(opts.cursor!==undefined)out+='<path d=\"M'+X(opts.cursor)+' 27V175\" stroke=\"var(--muted)\" stroke-dasharray=\"3 3\"/>';e.innerHTML=out+'</g>';e.dataset.curves=JSON.stringify(series.map(s=>s.pts));}const curve=(fn,lo,hi,n=120)=>Array.from({length:n+1},(_,i)=>{const x=lo+(hi-lo)*i/n;return[x,fn(x)]});function inputs(draw){document.querySelectorAll('input,select').forEach(e=>{e.addEventListener('input',draw);e.addEventListener('change',draw)});draw()}const n=id=>+$('#'+id).value;const show=(id,v,d=3)=>set(id,Number(v.toFixed(d)));let r=0,w=false,msg='initial';function draw(){cells('guards',[...Array.from({length:r},(_,i)=>({text:'Ref '+i,cls:'on'})),...(w?[{text:'RefMut',cls:'gold'}]:[])]);set('state',w?'exclusive':r?'shared × '+r:'unborrowed');$('#read').disabled=r>=4;$('#last').disabled=!r&&!w;$('#dropRead').disabled=!r;$('#dropWrite').disabled=!w;set('explanation',t(msg));document.body.dataset.readers=r;document.body.dataset.writer=w;}for(let id of ['read','write','last','dropRead','dropWrite','reset'])$('#'+id).onclick=()=>{msg='ok';if(id==='read'){if(w)msg='bad';else r++}if(id==='write'){if(w||r)msg='bad';else w=true}if(id==='last')msg='used';if(id==='dropRead'){r--;msg='dropped'}if(id==='dropWrite'){w=false;msg='dropped'}if(id==='reset'){r=0;w=false;msg='initial'}draw()};draw();","audio":false,"strings":{"bad":"Err:存在冲突 guard;try_ 系列不会等待。","dropRead":"释放一个 Ref","dropWrite":"释放 RefMut","dropped":"guard 已释放,对应动态借用结束。","guards":"仍存活的 guard","heading":"最后读取之后,guard 还在吗?","initial":"没有 guard;共享或独占借用均可申请。","intro":"直接申请共享或独占借用,再显式释放 guard。","last":"读取一次","ok":"成功:创建了需要释放的 guard。","read":"try_borrow()","reset":"重置","scope":"仅模拟未分裂 guard 的 try_borrow/try_borrow_mut;冲突返回错误,不等待也不执行真实 Rust。","scopeLabel":"模型范围与约定","state":"借用状态","used":"读取不会自动 drop guard;再次尝试独占借用仍可能失败。","write":"try_borrow_mut()"}}
Mutex 把独占访问扩展到线程间
std::sync::Mutex::lock 等待获得锁,返回 LockResult<MutexGuard>。guard 的释放解锁;锁保护的是遵循同一协议的数据访问,不能让一部分代码绕开锁仍期待一致性。
try_lock 不阻塞,返回的是 TryLockResult,即 Result,错误区分 WouldBlock 和 Poisoned。下面在另一个线程持锁时验证竞争分支,避免同线程递归加锁的未规定行为:
use std:: sync:: { Mutex, TryLockError, mpsc} ;
use std:: thread;
fn main ( ) {
let value = Mutex:: new( 1 ) ;
thread:: scope( | scope | {
let ( ready_tx, ready_rx) = mpsc:: channel( ) ;
let ( done_tx, done_rx) = mpsc:: channel( ) ;
let shared = & value;
scope.spawn ( move | | {
let mut guard = shared.lock ( ) .unwrap ( ) ;
ready_tx.send ( ( ) ) .unwrap ( ) ;
done_rx.recv ( ) .unwrap ( ) ;
* guard + = 1 ;
} ) ;
ready_rx.recv ( ) .unwrap ( ) ;
assert! ( matches! ( value.try_lock ( ) , Err ( TryLockError:: WouldBlock) ) ) ;
done_tx.send ( ( ) ) .unwrap ( ) ;
} ) ;
assert_eq! ( * value.lock ( ) .unwrap ( ) , 2 ) ;
}
poison 提醒调用者此前有持锁线程在 panic 展开期间离开临界区,业务状态可能不完整。它是建议性的检测,不是完整的安全证明;恢复时要评估不变量,不能无条件忽略,也不能让 unsafe 代码仅依赖 poison 避免 UB。Mutex
底层实现依赖平台和标准库版本,不能固定说 Linux 上总是 pthread_mutex_t。选择它主要依赖其互斥契约,而非某次实现的内部字段。
获取 guard 检查余额与目标上限 计算新状态 所有可能失败的检查先完成 一起提交两个字段 释放 guard 后对外可见 其他参与者只能看到提交前或提交后的账本 前提:所有相关读取与修改都遵循这把锁的协议 同一把锁保护一次完整的状态转换 互斥保证临界区不交错;业务校验、错误时不修改和外部副作用仍需另外设计。
锁保护的是不变量,不只是一个变量
下面用一把锁保护两个账户余额,转账必须保持总额,并在余额不足或目标溢出时保持原状。先算出所有新值,再提交,可避免第一字段已修改、第二字段校验才失败。
use std:: sync:: Mutex;
# [ derive ( Debug, PartialEq, Eq ) ]
enum TransferError { Insufficient, Overflow }
fn transfer ( balances : & Mutex< ( u64 , u64 ) > , amount : u64 )
-> Result< ( ) , TransferError>
{
let mut state = balances.lock ( ) .unwrap ( ) ;
let left = state.0. checked_sub ( amount) .ok_or ( TransferError:: Insufficient) ? ;
let right = state.1. checked_add ( amount) .ok_or ( TransferError:: Overflow) ? ;
* state = ( left, right) ;
Ok ( ( ) )
}
fn main ( ) {
let balances = Mutex:: new( ( 100 , 20 ) ) ;
assert_eq! ( transfer ( & balances, 30 ) , Ok ( ( ) ) ) ;
assert_eq! ( * balances.lock ( ) .unwrap ( ) , ( 70 , 50 ) ) ;
assert_eq! ( transfer ( & balances, 80 ) , Err ( TransferError:: Insufficient) ) ;
assert_eq! ( * balances.lock ( ) .unwrap ( ) , ( 70 , 50 ) ) ;
let full = Mutex:: new( ( 10 , u64 :: MAX ) ) ;
assert_eq! ( transfer ( & full, 1 ) , Err ( TransferError:: Overflow) ) ;
assert_eq! ( * full.lock ( ) .unwrap ( ) , ( 10 , u64 :: MAX ) ) ;
}
示例将中毒视为不可恢复错误并 unwrap,适合展示算术与提交顺序;实际接口可另行返回锁错误或定义恢复策略。若给每个余额单独配一把锁,先后解锁会暴露中间状态;同时持有两把锁又需要统一加锁顺序来避免死锁。两个原子整数也不会自动构成一次原子转账。
锁内应包含维护不变量必需的读取和提交,但应慎重放入慢 I/O、未知回调或长时间计算。把计算移到锁外可缩短持锁时间,却要检查计算依赖的旧状态是否已经变化;必要时记录版本并在重新加锁后验证,不能默认锁外计算仍对应最新数据。
中毒不会回滚已经写入的数据
PoisonError 可以交还 guard,使调用者有机会检查和修复状态。仅调用 into_inner 是取出访问凭证;clear_poison 是清除标记,都不会自动恢复业务不变量。下面构造一次可控的线程 panic,再用已知完整状态替换损坏状态。
use std:: sync:: Mutex;
use std:: thread;
fn main ( ) {
let state = Mutex:: new( ( 50 u32 , 50 u32 ) ) ;
thread:: scope( | scope | {
let shared = & state;
let failed = scope.spawn ( move | | {
let mut guard = shared.lock ( ) .unwrap ( ) ;
guard.0 = 0 ;
panic! ( " 模拟只更新了一个字段" ) ;
} ) ;
assert! ( failed.join ( ) .is_err ( ) ) ;
} ) ;
assert! ( state.is_poisoned ( ) ) ;
{
let mut guard = match state.lock ( ) {
Ok ( _ ) => panic! ( " 预期收到中毒状态" ) ,
Err ( error) => error.into_inner ( ) ,
} ;
assert_eq! ( * guard, ( 0 , 50 ) ) ;
* guard = ( 50 , 50 ) ; state.clear_poison ( ) ;
}
assert! ( ! state.is_poisoned ( ) ) ;
assert_eq! ( * state.lock ( ) .unwrap ( ) , ( 50 , 50 ) ) ;
}
这个示例依赖 panic 展开并通过 join 观察线程失败;panic=abort 下进程会终止,无法按该流程恢复。现实中的余额不能凭空重置,需要可信快照、日志或业务对账。中毒检测本身也不是所有 panic 场景都必定触发的可靠性边界。Mutex poisoning
三者的选择边界
问题 Cell RefCell Mutex
通过 &self 修改 支持替换等操作 通过动态借用 通过持锁 guard
访问冲突 不维持普通共享借用 返回借用错误或 panic 等待或 try_lock 返回错误
T: Send 时整体 Send 是 是 是
可实现 Sync 否 否 T: Send 时是
只替换整个值时,Cell 往往简单;需要暂时借出内部结构且限定单线程时,RefCell 更合适;线程间维护多个字段共同不变量时,Mutex 通常容易推理。异步场景还要考虑等待是否阻塞执行器,以及 guard 是否跨 await,见 Tokio runtime 。