栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Rust多线程传递给Python是否会被GIL

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Rust多线程传递给Python是否会被GIL

#[pyfunction]
// 一个双线程,一个三线程,循环级别位10**10(999999999)
pub fn  multi_thread_1(){
    let thread1 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    let thread2 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    thread1.join();
    thread2.join();
}

#[pyfunction]
pub fn  multi_thread_2(){
    let thread1 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    let thread2 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    let thread3 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    thread1.join();
    thread2.join();
    thread3.join();
}

//将上面两个函数打包在一个模块给python
#[pymodule]
// 这一段的传参我有点看不懂,不过是固定模式应该
fn rust_give_python(_py: Python, m: &PyModule) -> PyResult<()>{
    m.add_function(wrap_pyfunction!(multi_thread_1, m)?)?;
    m.add_function(wrap_pyfunction!(multi_thread_2, m)?)?;
    Ok(())
}
[lib]
name = 'rust_give_python'
crate_type = ['cdylib']

[dependencies.pyo3]
version = "0.16.4"
features = ["auto-initialize"]

验证时刻;

import threading

# 这里Python数量级比Rust害小了10倍
def a():
    p: int = 0
    while p < 99999999:
        p += 1


def time_cal(somefuc):
    def fuc(*args):
        a_ = time.time()
        somefuc(*args)
        b_ = time.time()
        print(b_ - a_)
    return fuc

@time_cal
def test1():
    thread1 = threading.Thread(target=a)
    thread2 = threading.Thread(target=a)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

@time_cal
def test2():
    thread1 = threading.Thread(target=a)
    thread2 = threading.Thread(target=a)
    thread3 = threading.Thread(target=a)
    thread1.start()
    thread2.start()
    thread3.start()
    thread1.join()
    thread2.join()
    thread3.join()



if __name__ == '__main__':
    test1()
    test2()
    a = time.time()
    rust_give_python.multi_thread_1()
    b = time.time()
    rust_give_python.multi_thread_2()
    c = time.time()
    print(b - a, c - b)

结果:
11.623199033737183
17.019014596939087
5.623442649841309 5.721031188964844

这个结果很能说明问题:
11秒秒 和 17相差6,正好是一次循环的次数,说明Python多线程无法搞定并行,是串行的运行。 Rust编译保留了Rust快速的特性,同时时间上相差5.62和5.72,说明是真正的并行。
结论,我们之后可以尝试使用Rust优化Python多线程相关

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/869576.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号