在python中创建线程

在python中创建线程,python,multithreading,Python,Multithreading,我有一个脚本,我希望一个函数与另一个函数同时运行 我看到的示例代码如下: 导入线程 def MyThread(threading.thread): #做某事。。。。。。。。 def MyThread2(threading.thread): #做某事。。。。。。。。 MyThread().start() MyThread2().start() 我很难让它工作。我更喜欢使用线程函数而不是类来实现这一点 这是工作脚本: 从线程导入线程 类myClass(): def帮助(自我): 操作系统('./s

我有一个脚本,我希望一个函数与另一个函数同时运行

我看到的示例代码如下:

导入线程
def MyThread(threading.thread):
#做某事。。。。。。。。
def MyThread2(threading.thread):
#做某事。。。。。。。。
MyThread().start()
MyThread2().start()
我很难让它工作。我更喜欢使用线程函数而不是类来实现这一点

这是工作脚本:

从线程导入线程
类myClass():
def帮助(自我):
操作系统('./ssh.py')
def nope(自我):
a=[1,2,3,4,5,6,67,78]
对于我来说,在一个:
打印i
睡眠(1)
如果名称=“\uuuuu main\uuuuuuuu”:
Yep=myClass()
thread=thread(target=yesp.help)
thread2=线程(target=yesp.nope)
thread.start()
thread2.start()
thread.join()
打印“已完成”
是否覆盖了run()方法?如果重写了
\uuuuu init\uuuuu
,是否确保调用基本
线程.Thread.\uuuuu init\uuuu()

在启动两个线程之后,主线程是否继续在子线程上无限期地执行工作/阻塞/连接,以便在子线程完成任务之前主线程的执行不会结束


最后,您是否遇到任何未处理的异常?

您可以使用
线程
构造函数中的
目标
参数直接传入被调用的函数,而不是
运行

您不需要使用
线程
的子类来实现此功能-看看下面我发布的简单示例看看如何:

from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print("running")
        sleep(1)


if __name__ == "__main__":
    thread = Thread(target = threaded_function, args = (10, ))
    thread.start()
    thread.join()
    print("thread finished...exiting")

这里我展示了如何使用线程模块创建一个线程,该线程调用一个普通函数作为其目标。您可以看到我如何在线程构造函数中将所需的参数传递给它。

您的代码存在一些问题:

def MyThread ( threading.thread ):
  • 你不能用一个函数做子类;只有一节课
  • 如果要使用子类,则需要threading.Thread,而不是threading.Thread
如果您确实希望仅使用函数执行此操作,则有两个选项:

带螺纹:

import threading
def MyThread1():
    pass
def MyThread2():
    pass

t1 = threading.Thread(target=MyThread1, args=[])
t2 = threading.Thread(target=MyThread2, args=[])
t1.start()
t2.start()
带螺纹:

import thread
def MyThread1():
    pass
def MyThread2():
    pass

thread.start_new_thread(MyThread1, ())
thread.start_new_thread(MyThread2, ())

我试图添加另一个join(),但似乎成功了。这是代码

from threading import Thread
from time import sleep

def function01(arg,name):
    for i in range(arg):
        print(name,'i---->',i,'\n')
        print (name,"arg---->",arg,'\n')
        sleep(1)

def test01():
    thread1 = Thread(target = function01, args = (10,'thread1', ))
    thread1.start()
    thread2 = Thread(target = function01, args = (10,'thread2', ))
    thread2.start()
    thread1.join()
    thread2.join()
    print ("thread finished...exiting")

test01()

Python3具有以下功能:。这使我们的工作更容易

它已经为和

以下内容提供了一个见解:

线程池执行器示例

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))
import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()
另一个例子

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))
import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

没有未处理的异常,主线程应运行30分钟。我没有重写
\uuuu init\uuuuu
。那么需要run()吗?ThanksI刚刚意识到您的示例是
defMythread(threading.thread)
。。。我假设这些是类定义。如果要将threading.thread子类化,并使用
target=None
初始化thread对象,或省略
target
arg,则需要实现run()。否则,如果您只想在另一个线程中运行一个简单的任务,请参阅jkp的答案。我在上面添加了脚本。你能告诉我如何让第二个函数与第一个函数同时运行吗。Thanks@chrissygormley:join()阻塞直到第一个线程完成。@chrissygormley:如前所述,join阻塞直到要连接的线程完成,因此在您的情况下,以第二个函数为目标启动第二个线程,并排运行这两个函数,然后,如果您只想等待它们完成,可以选择加入其中一个。我一直在阅读
退出
作为
激动人心的
,我认为这更合适。第二个参数必须是