有四个线程,每个线程只打印一个数字,这四个数字分别是 1 2 3 4 ,现在要求你做到四个线程顺序打印 1 2 3 4 ,且每个线程都打印10次.
时间: 2023-11-27 13:52:02 浏览: 37
这个问题可以使用信号量来解决。具体实现如下:
```python
from threading import Thread, Semaphore
class Printer:
def __init__(self):
# 初始化信号量
self.sema1 = Semaphore(1) # 控制线程1和线程2的顺序
self.sema2 = Semaphore(0) # 控制线程2和线程3的顺序
self.sema3 = Semaphore(0) # 控制线程3和线程4的顺序
self.sema4 = Semaphore(0) # 控制线程4和线程1的顺序
def print_num(self, num, sema_cur, sema_next):
for i in range(10):
# 获取当前线程的信号量
sema_cur.acquire()
# 打印数字
print(num, end=' ')
# 释放下一个线程的信号量
sema_next.release()
if __name__ == '__main__':
printer = Printer()
t1 = Thread(target=printer.print_num, args=(1, printer.sema1, printer.sema2))
t2 = Thread(target=printer.print_num, args=(2, printer.sema2, printer.sema3))
t3 = Thread(target=printer.print_num, args=(3, printer.sema3, printer.sema4))
t4 = Thread(target=printer.print_num, args=(4, printer.sema4, printer.sema1))
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
```
输出结果为:
```
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
```
解释一下上述代码的实现过程:
- 首先创建一个 `Printer` 类,里面包含了四个信号量分别用于控制四个线程之间的顺序.
- `print_num` 方法打印数字,接收当前线程的信号量 `sema_cur` 和下一个线程的信号量 `sema_next`,在循环中先获取当前线程的信号量,打印数字,然后释放下一个线程的信号量。
- 在主程序中创建四个线程,分别对应 1、2、3、4 这四个数字,每个线程都调用 `print_num` 方法并传入相应的信号量,然后启动线程并等待所有线程结束。
这样就可以保证四个线程按照顺序打印数字了。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)