简体   繁体   English

Python class 作为线程,不打印输入

[英]Python class as thread, doesn't print input

I'm running Python 3 and are trying to create my own class for threads :我正在运行Python 3并尝试为threads创建自己的 class :

class myThread(multiprocessing.Process):
  def __init__(self, i):
    multiprocessing.Process.__init__(self)
    self.i = i
  def run(self):
    while True:
      print(self.i)

When creating the thread, it doesn't output i :创建线程时,它不会 output i

multiprocessing.Process(target=myThread, args=[5]).start()

You have to create instances from the class that inherits from threading.Thread and use the start method in order to start the block in the def run() block:您必须从继承自threading.Thread的 class 创建实例,并使用 start 方法在def run()块中启动块:

import threading

class myThread(threading.Thread):
  def __init__(self, i):
    threading.Thread.__init__(self)
    self.i = i
  def run(self):
    while True:
      print(self.i)



for num in range(5): # number of threads to create
    _definition = myThread(i = 'myoutput')
    _definition.start()

The issue is that this only creates a thread in the process.问题是这只会在进程中创建一个线程。 It doesn't start that thread.它不会启动该线程。

multiprocessing.Process(target=myThread, args=[5])

You could do the following but the combination of a Thread and a Process in this manner is somewhat redundant as one could have used the main Thread of the Process instead.您可以执行以下操作,但以这种方式组合线程和进程有点多余,因为可以使用进程的主线程。

import threading
import multiprocessing

class myThread(threading.Thread):
  def __init__(self, i):
    threading.Thread.__init__(self)
    self.i = i
  def run(self):
    while True:
      print(self.i)

def wrapper(i):
    t = myThread(i)
    t.start()
    t.join()

if __name__=="__main__":
    p = multiprocessing.Process(target=wrapper, args=[5])
    p.start()
    p.join()

The following does the same but without the Thread:以下内容相同,但没有线程:

import multiprocessing

def my_target(i):
    while True:
        print(self.i)

if __name__=="__main__":
    p = multiprocessing.Process(target=my_target, args=[5])
    p.start()
    p.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM