未并行处理的Python线程

Python Threading not processed parallel(未并行处理的Python线程)
本文介绍了未并行处理的Python线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的中间人,我想以并行模式运行几个相同的类实例,用于获取数据和为金融市场做出决策。为了继续我的想法,我运行下面的代码来看看Python是如何工作的,它似乎可以运行一次完整的第一类实例和第二类实例,我想并行运行它,我如何才能...? 以下是用于测试的一些示例代码..

import threading
import time

class thr(object):

  def __init__(self, name):
     self.name = name
     self.x = 0

  def run(self):
     for i in list(range(10)):
         self.x +=1
         print("something {0} {1}".format(self.name, self.x))
         time.sleep(1)            

F = thr("First")
S = thr("Second")

threading.Thread(target=F.run())
threading.Thread(target=S.run())

和结果如下...

something First 1
something First 2
something First 3
something First 4
something First 5
something First 6
something First 7
something First 8
something First 9
something First 10
something Second 1
something Second 2
something Second 3
something Second 4
something Second 5
something Second 6
something Second 7
something Second 8
something Second 9
something Second 10
Out[27]: <Thread(Thread-25, initial)>

推荐答案

问题在这里:

threading.Thread(target=F.run())
threading.Thread(target=S.run())

target=接受可调用对象或NoneF.run()立即执行F.run,等待其完成,然后传递返回值(run()方法中的None)作为目标。

您想要这样的内容:

t1 = threading.Thread(target=F.run)
t2 = threading.Thread(target=S.run)
t1.start()
t2.start()

请注意,run后面没有括号

以下是带有建议更改的完整程序:

import threading
import time

class thr(object):

  def __init__(self, name):
     self.name = name
     self.x = 0

  def run(self):
     for i in list(range(10)):
         self.x +=1
         print("something {0} {1}".format(self.name, self.x))
         time.sleep(1)            

F = thr("First")
S = thr("Second")

t1 = threading.Thread(target=F.run)
t2 = threading.Thread(target=S.run)
t1.start()
t2.start()

和输出(Python3.6.1):

$ python sf.py
something First 1
something Second 1
something Second 2
something First 2
something Second 3
something First 3
something Second 4
something First 4
something Second 5
something First 5
something Second 6
something First 6
something Second 7
something First 7
something First 8
something Second 8
something First 9
something Second 9
something First 10
something Second 10

这篇关于未并行处理的Python线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)