多线程案例

以下是一个简单的多线程案例,实现了一个简单的计数器程序。该程序会同时启动两个线程,每个线程都会对计数器进行加一操作,并输出当前计数器的值。

python 复制代码
import threading

# 定义一个全局变量作为计数器
counter = 0

# 定义一个线程锁,用于对计数器进行互斥操作
lock = threading.Lock()

# 定义一个线程函数,每次将计数器加1,并输出当前计数器的值
def increment():
    global counter
    with lock:
        counter += 1
    print("Current counter value: {}".format(counter))

# 创建两个线程
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)

# 启动线程
t1.start()
t2.start()

# 等待线程执行完毕
t1.join()
t2.join()

当程序运行时,输出如下:

复制代码
Current counter value: 1
Current counter value: 2

可以看到,两个线程同时对计数器进行加一操作,并输出了当前计数器的值。由于使用了线程锁,保证了计数器的操作互斥,避免了数据竞争的问题。

相关推荐
SmallBambooCode12 小时前
【人工智能】【Python】离线环境下huggingface预训练权重导入流程
开发语言·人工智能·python
Yeh20205813 小时前
Mybatis笔记一
java·笔记·mybatis
likerhood13 小时前
Java 动态代理深度解析:从“为什么“到“底层原理“
java
_阿伟_13 小时前
信息检索简单介绍
java
下次再写13 小时前
深入浅出微服务架构:从理论到Spring Boot实战
java·微服务·springboot·springcloud·架构设计·后端开发·分布式系统
djarmy13 小时前
C 标准库 `<stdio.h>` 完整函数清单(官方标准 + 常用全部函数)
c语言·c++·算法
七牛云行业应用13 小时前
NotebookLM 手机版上线了,这份完整指南帮你把它用起来
算法
夕除13 小时前
spring boot--08
开发语言·windows·python
进阶的猿猴13 小时前
Rsa简单实现接口到期限制(springBoot)
java·spring boot·后端