莫待无花空折枝 发表于 2020-6-11 11:14:22

lock

import threading
import random
import time

lock = threading.Lock
list1 = *10
def task1():
    lock.acquire()
    for i in range(len(list1)):
      list1 = 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'


但我看是有这个方法的呀
class Lock:
    def __init__(self) -> None: ...
    def __enter__(self) -> bool: ...
    def __exit__(self, exc_type: Optional],
               exc_val: Optional,
               exc_tb: Optional) -> Optional: ...
    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: ...
为什么不能用

Twilight6 发表于 2020-6-11 11:18:07

两个错误,第一个:
lock = threading.Lock
改成:
lock = threading.Lock()
第二个 time模块:
import time
改成:
from time import sleep
完整代码:
import threading
import random
from time import sleep

lock = threading.Lock()
list1 = *10
def task1():
    lock.acquire()
    for i in range(len(list1)):
      list1 = 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)
页: [1]
查看完整版本: lock