十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章主要介紹“Java有鎖并發(fā)、無鎖并發(fā)和CAS實(shí)例分析”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“Java有鎖并發(fā)、無鎖并發(fā)和CAS實(shí)例分析”文章能幫助大家解決問題。

臨海ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!
std::sync::Mutex
。(加上Arc是為了能讓多個(gè)線程都擁有棧的所有權(quán))
use std::sync::{Mutex, Arc};
#[derive(Clone)]
struct ConcurrentStack {
inner: Arc>>,
}
impl ConcurrentStack {
pub fn new() -> Self {
ConcurrentStack {
inner: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn push(&self, data: T) {
let mut inner = self.inner.lock().unwrap();
(*inner).push(data);
}
pub fn pop(&self) -> Option {
let mut inner = self.inner.lock().unwrap();
(*inner).pop()
}
}
std::sync::atomic
中的類型就提供了CAS操作,比如原子指針
std::sync::atomic::AtomicPtr
pub fn compare_and_swap(
&self,
current: *mut T,
new: *mut T,
order: Ordering
) -> *mut T
Acquire
,
Release
,
Relaxed
)
#![feature(box_raw)]
use std::ptr::{self, null_mut};
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::Ordering::{Relaxed, Release, Acquire};
pub struct Stack {
head: AtomicPtr>,
}
struct Node {
data: T,
next: *mut Node,
}
impl Stack {
pub fn new() -> Stack {
Stack {
head: AtomicPtr::new(null_mut()),
}
}
pub fn pop(&self) -> Option {
loop {
// 快照
let head = self.head.load(Acquire);
// 如果棧為空
if head == null_mut() {
return None
} else {
let next = unsafe { (*head).next };
// 如果現(xiàn)狀較快照并沒有發(fā)生改變
if self.head.compare_and_swap(head, next, Release) == head {
// 讀取內(nèi)容并返回
return Some(unsafe { ptr::read(&(*head).data) })
}
}
}
}
pub fn push(&self, t: T) {
// 創(chuàng)建node并轉(zhuǎn)化為*mut指針
let n = Box::into_raw(Box::new(Node {
data: t,
next: null_mut(),
}));
loop {
// 快照
let head = self.head.load(Relaxed);
// 基于快照更新node
unsafe { (*n).next = head; }
// 如果在此期間,快照仍然沒有過時(shí)
if self.head.compare_and_swap(head, n, Release) == head {
break
}
}
}
}
return Some(unsafe { ptr::read(&(*head).data) })head
,這是一個(gè)內(nèi)存泄漏!哎,看來無鎖并發(fā)好不容易呢。關(guān)于“Java有鎖并發(fā)、無鎖并發(fā)和CAS實(shí)例分析”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。