rust怎么在上门锁密码_通过例子学习 Go 和 Rust ---- Mutex 互斥锁

互斥锁是并发编程的时候会用到的东西,它表示一份数据不可以被两个进程同时访问.

Go

// A Mutex is a mutual exclusion lock.

// The zero value for a Mutex is an unlocked mutex.

//

// A Mutex must not be copied after first use.

type Mutex struct {

state int32

sema uint32

}

// Lock locks m.

// If the lock is already in use, the calling goroutine

// blocks until the mutex is available.

func (m *Mutex) Lock() {

// Fast path: grab unlocked mutex.

if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {

if race.Enabled {

race.Acquire(unsafe.Pointer(m))

}

return

}

// Slow path (outlined so that the fast path can be inlined)

m.lockSlow()

}

举个栗子

import (

"sync"

)

const (

N = 10

)

func main() {

data := 0

var lock sync.Mutex

done := make(chan bool)

for i := 0; i < N; i++ {

go func() {

lock.Lock()

data += 1

if data == N {

done

}

lock.Unlock()

}()

}

}

Rust

pub struct Mutex {

// Note that this mutex is in a *box*, not inlined into the struct itself.

// Once a native mutex has been used once, its address can never change (it

// can't be moved). This mutex type can be safely moved at any time, so to

// ensure that the native mutex is used correctly we box the inner mutex to

// give it a constant address.

inner: Box<:mutex>,

poison: poison::Flag,

data: UnsafeCell,

}

impl Mutex {

pub fn lock(&self) -> LockResult> {

unsafe {

self.inner.raw_lock();

MutexGuard::new(self)

}

}

}

pub struct MutexGuard {

lock: &'a Mutex,

poison: poison::Guard,

}

impl Drop for MutexGuard {

#[inline]

fn drop(&mut self) {

unsafe {

self.lock.poison.done(&self.poison);

self.lock.inner.raw_unlock();

}

}

}

又举个栗子

use std::sync::{Arc, Mutex};

use std::thread;

use std::sync::mpsc::channel;

fn main() {

const N: usize = 10;

let data = Arc::new(Mutex::new(0));

let (tx, rx) = channel();

for _ in 0..N {

let (data, tx) = (Arc::clone(&data), tx.clone());

thread::spawn(move || {

let mut data = data.lock().unwrap();

*data += 1;

if *data == N {

tx.send(()).unwrap();

}

});

}

println!("{:?}", rx.recv().unwrap());

}

有疑问加站长微信联系(非本文作者)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值