我一直在努力应对多线程程序。我目前的理解是当我创建多个线程时,它将并行运行。但它没有发生。
这是我到目前为止的代码。
#!/usr/bin/python
import threading
import time
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
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
print "Exiting " + self.name
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = 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()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
输出:
Starting Thread-1
Starting Thread-2
Thread-1: Mon Nov 16 23:49:33 2015
Thread-1: Mon Nov 16 23:49:34 2015
Thread-1: Mon Nov 16 23:49:35 2015
Exiting Thread-1
Thread-2: Mon Nov 16 23:49:37 2015
Thread-2: Mon Nov 16 23:49:39 2015
Thread-2: Mon Nov 16 23:49:41 2015
Exiting Thread-2
Exiting Main Thread
我除了两个线程都要并行运行。但它没有发生。请帮我理解多线程程序,因为我是python中多线程程序的新手。提前致谢
答案 0 :(得分:3)
在每个帖子中打印之前,您获得了共享锁。所以他们当然没有交错print
s,当第一个获取它的线程休眠时,锁定没有被释放,所以第二个线程一直等待锁定。“ / p>
如果目标是仅保护时间打印,而不是从开始到结束的打印循环,则您需要将run
和print_time
的代码更改为:
def run(self):
print "Starting " + self.name
# No locking now, letting print_time do it
print_time(self.name, self.counter, 3)
print "Exiting " + self.name
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
# Use a with statement to avoid problems with lock being held forever
# if release() call skipped due to an exception (or coding error)
with threadLock: # Hold lock during time and print, and at no other time
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
答案 1 :(得分:1)
顺便说一下:
CPython实现细节:在CPython中,由于Global Interpreter Lock,只有一个线程可以同时执行Python代码(即使某些面向性能的库可能会克服此限制)。如果您希望应用程序更好地利用多核计算机的计算资源,建议您使用多处理或concurrent.futures.ProcessPoolExecutor。但是,如果要同时运行多个I / O绑定任务,则线程仍然是一个合适的模型。
无论有没有锁,都无法获得真正的并行性。您必须使用multiprocessing。