簡體   English   中英

Python class 作為線程,不打印輸入

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

我正在運行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)

創建線程時,它不會 output i

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

您必須從繼承自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()

問題是這只會在進程中創建一個線程。 它不會啟動該線程。

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

您可以執行以下操作,但以這種方式組合線程和進程有點多余,因為可以使用進程的主線程。

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()

以下內容相同,但沒有線程:

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