多线程获取/释放不起作用

时间:2018-11-25 12:31:11

标签: python-3.x multithreading

我编写了一个非常简单的程序来启动,运行和退出线程。为了进行同步,我使用了acquire()和release()方法。问题是尽管我的IDE建议“ threading.Lock”具有方法“ acquire()”和“ release()”。由于我能够成功导入它们,但是当我执行整个代码时,出现以下错误:

Starting Thread-1
Starting Thread-2
Exiting Main Thread
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:/Users/AmiteshSahay/PycharmProjects/WebApp/palindrome.py", line 16, in run
    threading.Lock.acquire()
AttributeError: 'builtin_function_or_method' object has no attribute 'acquire'

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:/Users/AmiteshSahay/PycharmProjects/WebApp/palindrome.py", line 16, in run
    threading.Lock.acquire()
AttributeError: 'builtin_function_or_method' object has no attribute 'acquire'

下面是代码段

import threading
import time

exitFlag = 0


class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("Starting " + self.name)
        threading.Lock.acquire()
        print_time(self.name, self.counter, 5)
        print("Exiting " + self.name)
        threading.Lock.release()


def print_time(threadName, delay, counter):
        while counter:
            if exitFlag:
                threadName.exit()
                time.sleep(delay)
            print("%s: %s" % (threadName,  time.ctime(time.time())))
            counter -= 1


new_thread = threading.Lock()
threads = []
# Create new threads

thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

# adding threads to the new list

threads.append(thread1)
threads.append(thread2)

# wait for all the threads to complete

for i in threads:
    i.join()
print("Exiting Main Thread")

注意:

我正在使用PyCharm IDE Python 3.6

0 个答案:

没有答案