|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import threading
- import random
- import time
- lock = threading.Lock
- list1 = [0]*10
- def task1():
- lock.acquire()
- for i in range(len(list1)):
- list1[i] = 1
- sleep(0.1)
- lock.release()
- def task2():
- lock.acquire()
- for i in range(len(list1)):
- print('------',i)
- sleep(0.1)
- lock.release()
- if __name__ == '__main__':
- th1 = threading.Thread(target=task1)
- th2 = threading.Thread(target=task2)
- th1.start()
- th2.start()
- th1.join()
- th2.join()
- print(list1)
复制代码
结果
- File "D:\python3.7\Lib\threading.py", line 865, in run
- self._target(*self._args, **self._kwargs)
- File "E:/python_pycharm/进阶学习/threading03.py", line 16, in task2
- lock.acquire()
- AttributeError: 'builtin_function_or_method' object has no attribute 'acquire'
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
复制代码
但我看是有这个方法的呀
- class Lock:
- def __init__(self) -> None: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, exc_type: Optional[Type[BaseException]],
- exc_val: Optional[BaseException],
- exc_tb: Optional[TracebackType]) -> Optional[bool]: ...
- if sys.version_info >= (3,):
- def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ...
- else:
- def acquire(self, blocking: bool = ...) -> bool: ...
- def release(self) -> None: ...
- def locked(self) -> bool: ...
复制代码
为什么不能用
两个错误,第一个:
改成:
第二个 time模块:
改成:
完整代码:
- import threading
- import random
- from time import sleep
- lock = threading.Lock()
- list1 = [0]*10
- def task1():
- lock.acquire()
- for i in range(len(list1)):
- list1[i] = 1
- sleep(0.1)
- lock.release()
- def task2():
- lock.acquire()
- for i in range(len(list1)):
- print('------',i)
- sleep(0.1)
- lock.release()
- if __name__ == '__main__':
- th1 = threading.Thread(target=task1)
- th2 = threading.Thread(target=task2)
- th1.start()
- th2.start()
- th1.join()
- th2.join()
- print(list1)
复制代码
|
|