编写线程出入栈数据python
时间: 2023-08-11 11:40:21 浏览: 49
以下是一个基于 Python 的线程出入栈数据的示例代码:
```python
import threading
class Stack:
def __init__(self):
self.stack = []
self.lock = threading.Lock()
def push(self, item):
with self.lock:
self.stack.append(item)
def pop(self):
with self.lock:
return self.stack.pop()
def producer(stack):
for i in range(10):
stack.push(i)
print('Producer: pushed', i)
def consumer(stack):
for i in range(10):
item = stack.pop()
print('Consumer: popped', item)
if __name__ == '__main__':
stack = Stack()
t1 = threading.Thread(target=producer, args=(stack,))
t2 = threading.Thread(target=consumer, args=(stack,))
t1.start()
t2.start()
t1.join()
t2.join()
```
在这段代码中,我们定义了一个 Stack 类,其中包含 push 和 pop 两个方法,用于往栈中添加数据和从栈中取出数据。为了保证线程安全,我们使用了 threading.Lock 对象来进行加锁。
在主程序中,我们创建了两个线程,一个用于往栈中添加数据,一个用于从栈中取出数据。通过启动这两个线程,我们可以模拟多个线程同时对栈进行读写的情况。