Python,线程在使用线程锁时以随机顺序开始
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python,线程在使用线程锁时以随机顺序开始,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1593字,纯文字阅读大概需要3分钟。
内容图文
![Python,线程在使用线程锁时以随机顺序开始](/upload/InfoBanner/zyjiaocheng/819/adb53bcfc0524ee19af971fdcc3d032f.jpg)
这里真的是Python的新手,并试图让我的头脑绕线程.我有代码:
import threading, time
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
super(myThread, self).__init__()
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting ", self.name
threadLock.acquire()
print_time(self.name , self.counter, 3)
#Free the lock to release the next thread
print "%s released, ready for the next thread"%self.name
threadLock.release()
class sillyThread(threading.Thread):
def run(self):
threadLock.acquire()
print "silly silly!"
time.sleep(2)
print "Silly silly!"
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s"%(threadName, time.ctime())
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
thread3 = sillyThread()
thread1.start()
thread2.start()
thread3.start()
threads.append(thread1)
threads.append(thread2)
threads.append(thread3)
# Wait for all threads to complete
for t in threads:
t.join()
print "%s is finished"%t.name
print "Exiting Main Thread"
我希望线程1首先启动,线程2和线程3放在块上,直到线程1完成.所以执行的顺序是线程1,线程2和线程3.但是每次运行代码时它都会有所不同.例如,有时Thread-3将首先运行,因为我首先调用thread1.start()行,然后它应该被锁定,因此没有意义.有人可以给我一些指示,说明为什么会这样吗?
解决方法:
Thread.start只是安排一个线程开始.它实际上并没有在那时开始.相反,从那时起,操作系统将接管并启动线程,因为它看起来与您的主线程异步.
如果您确实想要同步线程的运行,则需要使用互斥或??其他同步原语来自行完成.
内容总结
以上是互联网集市为您收集整理的Python,线程在使用线程锁时以随机顺序开始全部内容,希望文章能够帮你解决Python,线程在使用线程锁时以随机顺序开始所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。