我已經撰寫了一些代碼來將計算的獨立塊分解為多個片段,然后將每個片段提供給執行緒池,然后由執行緒池進行計算并將結果通過mpsc.
代碼如下:
pub fn impute(pbwt_data : Arc<&pbwt::PbwtInfo>, test_sequences : Vec<Vec<u8>>) -> Vec<Vec<u8>> {
let N = test_sequences.len();
let mut fin_imputed: Vec<Vec<u8>> = vec![Vec::new();N];
let safe_pbwt = Arc::new(pbwt_data);
let (tx,rx) = mpsc::channel();
let pool = ThreadPool::new(8);
let mut i = 0;
for tst_seq in test_sequences.into_iter(){
let txr = tx.clone();
let safe_test_seq = Arc::new(tst_seq);
let refer = Arc::clone(&safe_pbwt);
let clo = closure!(move txr, move refer, move safe_test_seq, || {
let val = impute_single(&refer,&safe_test_seq);
let ret = RowWPos { position: i as u32, row: val};
txr.send(ret).unwrap();
});
pool.execute(clo);
i = 1;
}
drop(tx);
for recd in rx.iter() {
fin_imputed[recd.position as usize] = recd.row;
}
return fin_imputed;
}
內部impute_single函式接受對PbwtInfo物件的參考和對物件的參考Vec<u8>。內部函式不會PbwtInfo以任何方式修改物件,它只是從中讀取。
不幸的是,當我嘗試運行它時,此代碼會產生錯誤:
error[E0521]: borrowed data escapes outside of function
--> pbwt_hkhan/src/imputer.rs:138:9
|
111 | pub fn impute(pbwt_data : Arc<&pbwt::PbwtInfo>, test_sequences : Vec<Vec<u8>>) -> Vec<Vec<u8>> {
| --------- - let's call the lifetime of this reference `'1`
| |
| `pbwt_data` is a reference that is only valid in the function body
...
138 | pool.execute(clo);
| ^^^^^^^^^^^^^^^^^
| |
| `pbwt_data` escapes the function body here
| argument requires that `'1` must outlive `'static`
For more information about this error, try `rustc --explain E0521`.
error: could not compile `pbwt_hkhan` due to previous error
我可以通過將函式pbwt_data : Arc<&pbwt::PbwtInfo> 簽名中pbwt_data : Arc<pbwt::PbwtInfo>的 然而,這意味著我的物件現在卡在 Arc 內,并且下游還有更多代碼,我想再次使用該物件。ArcPbwtInfoPbwtInfo
我可以克隆它,但它是一個相當大且昂貴的物件來創建一個副本,所以我寧愿不這樣做。理想情況下,我想要一個解決方案,我什至不必將 Arc 傳遞給impute函式,并且可以&PbwtInfo像 nothing it 或任何它呼叫的任何內容都可以修改pbwt_data。我知道我可以做到這一點,而不是將計算分成塊并使用執行緒池,我只使用單個執行緒,所以我覺得在這里應該是可能的。
uj5u.com熱心網友回復:
用作Arc<pbwt::PbwtInfo>型別。Arc::try_unwrap(your_arc)要再次檢索物件,如果只剩下 1 個強參考,您可以使用which 將給該物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/533126.html
標籤:多线程锈线程池引用计数
上一篇:如何將文本與元素的開頭對齊
