写一个将类当作多线程传递参数的值代码示例,并在线程中用到这个类
时间: 2024-02-24 20:53:21 浏览: 22
好的,下面是一个使用类作为多线程参数的示例代码,其中包含一个类`MyClass`,这个类中包含一个成员变量`value`和两个方法,一个用于修改value的值,一个用于获取value的值。
```python
import threading
class MyClass:
def __init__(self, value):
self.value = value
self.lock = threading.Lock()
def set_value(self, new_value):
with self.lock:
self.value = new_value
def get_value(self):
with self.lock:
return self.value
```
在这个示例中,我们使用了`threading.Lock()`来保证在多个线程中修改和读取`value`值的时候是线程安全的。
现在,我们来看看如何在多个线程中使用这个类:
```python
def worker(my_class):
for i in range(5):
value = my_class.get_value()
print(f"Thread {threading.current_thread().name} got value: {value}")
my_class.set_value(value+1)
if __name__ == "__main__":
my_class = MyClass(0)
threads = []
for i in range(3):
thread = threading.Thread(target=worker, args=(my_class,), name=f"Thread-{i}")
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
```
在这个示例中,我们创建了三个线程,并且将`my_class`对象作为参数传递给每个线程。每个线程执行`worker`函数,这个函数中先获取`value`的值,然后打印出来,然后将`value`的值加1,最后再将新的`value`值设置回`my_class`对象中。
运行这个示例代码,你会发现三个线程会并发执行,每个线程会获取到`value`的当前值,并将其加1,最终输出的结果会是:
```
Thread Thread-0 got value: 0
Thread Thread-1 got value: 1
Thread Thread-2 got value: 2
Thread Thread-2 got value: 3
Thread Thread-0 got value: 1
Thread Thread-1 got value: 2
Thread Thread-2 got value: 4
Thread Thread-0 got value: 2
Thread Thread-1 got value: 3
Thread Thread-2 got value: 5
Thread Thread-0 got value: 3
Thread Thread-1 got value: 4
```
可以看到,每个线程都可以正确的获取到`value`的值,并且在多个线程之间修改`value`的值也是线程安全的。