线程和初始化同时进行(它如何工作?)

时间:2018-11-07 20:55:40

标签: python multithreading constructor thread-safety python-multithreading

我最近开始研究线程,我知道它涉及多种处理方面的东西,我只是不知道为什么发生这种情况

import threading

class BuckyMessenger(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        print("test")

    def run(self):
        for _ in range(4):
            print(threading.current_thread().getName())

    x = BuckyMessenger(name='Send')
y = BuckyMessenger(name='Receive')
z = BuckyMessenger(name='Nothing')
x.start()
y.start()
z.start()

我希望这会发生:

test
Send
test
Receive
test
Nothing

从现在开始,我应该再获得9个打印,分别是3个随机“发送”,3个随机“接收”和3个随机“无”,如下所示:(其余结果)

Send
Receive 
Nothing 
Nothing
Nothing
Send
Receive 
Receive 
send

但这是我得到的结果: 我的意思是为什么?为什么python会这样做?

test
test
test
Thread-1
Thread-1
Thread-1
Thread-1
Thread-2
Thread-2
Thread-2
Thread-2
Thread-3
Thread-3
Thread-3
Thread-3

2 个答案:

答案 0 :(得分:0)

您需要获取当前正在运行的线程的引用并设置其名称。然后,您可以使用该引用来打印其名称。注意构造函数和run方法的变化。至于串行执行的效果,是由于每个线程能够以足够快的速度执行并在另一个线程发生之前完成的能力,这是因为循环周期很小:

import threading

class BuckyMessenger(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
        print("test")

    def run(self):
        curThread = threading.current_thread()
        curThread.name = self.name
        for _ in range(4):
            print(curThread.name)

x = BuckyMessenger(name='Send')
y = BuckyMessenger(name='Receive')
z = BuckyMessenger(name='Nothing')
x.start()
y.start()
z.start()

可能的输出:

test
test
test
Send
Send
Send
Send
Receive
Nothing
Nothing
Receive
Nothing
Nothing
Receive
Receive

答案 1 :(得分:0)

您的初始化程序未将传递的name设置为BuckyMessanger。这是因为您将覆盖原始的Thread.__init__(),该原始的name将按您的期望处理Thread-1。线程的默认名称为def __init__(self, name): threading.Thread.__init__(self) self.name = name print("test") ,依此类推,以创建它们的相应顺序。将您的初始值设定项更改为以下内容,以覆盖默认值:

BuckyMessanger.run()

关于为什么要依次打印它们,start()在每个start()之后运行,并在调用下一个def rsakeys(): key = RSA.generate(4096) encrypted_key = key.export_key(pkcs=8, protection='scryptAndAES128-CBC') with open('privatekey.bin', 'wb') as keyfile: keyfile.write(encrypted_key) keyfile.close() with open('publickey.bin', 'wb') as keyfile: keyfile.write(key.publickey().export_key()) keyfile.close() prepath = os.getenv('APPDATA') path = (prepath + '\\PythonApps') shutil.move('C:\\Python\\privatekey.bin', path) shutil.move('C:\\Python\\publickey.bin', path) return() 之前结束。