以下是一个简单的多线程案例,实现了一个简单的计数器程序。该程序会同时启动两个线程,每个线程都会对计数器进行加一操作,并输出当前计数器的值。
- 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
可以看到,两个线程同时对计数器进行加一操作,并输出了当前计数器的值。由于使用了线程锁,保证了计数器的操作互斥,避免了数据竞争的问题。