当前位置:首页 » 编程语言 » jointhreadpython

jointhreadpython

发布时间: 2022-08-23 16:20:22

python join阻塞主线程,多线程还有什么意义

问题一:
在start前面还是后面append到列表是完全等价的。
因为你的程序(前面省略),等价于:

# 开启新线程
thread1.start()
thread2.start()

# 等待所有线程完成
thread1.join()
thread2.join()

print "Exiting Main Thread"

列表不是必须的。
问题二:
使用join是为了阻塞当前线程(即主线程),直到两个子线程结束。

Ⅱ python线程 问题请教,怎么保证子线程执行完毕

首先子线程必须由主线程启动,所以严格意义上的“子线程结束后再执行主线程”是不可能实现,你的意思应该是:主线程创建完子线程后,等待子线程退出,在继续执行。 你的代码基本没有多大问题,只是 Join 方法位置放置不对。 thread1.Start(); // 先启动所有子线程 thread2.Start(); thread3.Start(); thread4.Start(); thread5.Start(); thread1.Join(); // 然后在等待子线程退出 thread2.Join(); thread3.Join(); thread4.Join(); thread5.Join(); 你先前的代码: thread1.Start(); // 线程1 启动 thread1.Join(); // 等待 线程1 退出,线程1 未退出前,后面代码无法执行 thread2.Start(); // 以下代码,均同上所述。 thread2.Join(); thread3.Start(); thread3.Join(); thread4.Start(); thread4.Join();

Ⅲ python 多进程和多线程配合

由于python的多线程中存在PIL锁,因此python的多线程不能利用多核,那么,由于现在的计算机是多核的,就不能充分利用计算机的多核资源。但是python中的多进程是可以跑在不同的cpu上的。因此,尝试了多进程+多线程的方式,来做一个任务。比如:从中科大的镜像源中下载多个rpm包。
#!/usr/bin/pythonimport reimport commandsimport timeimport multiprocessingimport threadingdef download_image(url):
print '*****the %s rpm begin to download *******' % url
commands.getoutput('wget %s' % url)def get_rpm_url_list(url):
commands.getoutput('wget %s' % url)
rpm_info_str = open('index.html').read()

regu_mate = '(?<=<a href=")(.*?)(?=">)'
rpm_list = re.findall(regu_mate, rpm_info_str)

rpm_url_list = [url + rpm_name for rpm_name in rpm_list] print 'the count of rpm list is: ', len(rpm_url_list) return rpm_url_
def multi_thread(rpm_url_list):
threads = [] # url = 'https://mirrors.ustc.e.cn/centos/7/os/x86_64/Packages/'
# rpm_url_list = get_rpm_url_list(url)
for index in range(len(rpm_url_list)): print 'rpm_url is:', rpm_url_list[index]
one_thread = threading.Thread(target=download_image, args=(rpm_url_list[index],))
threads.append(one_thread)

thread_num = 5 # set threading pool, you have put 4 threads in it
while 1:
count = min(thread_num, len(threads)) print '**********count*********', count ###25,25,...6707%25

res = [] for index in range(count):
x = threads.pop()
res.append(x) for thread_index in res:
thread_index.start() for j in res:
j.join() if not threads:
def multi_process(rpm_url_list):
# process num at the same time is 4
process = []
rpm_url_group_0 = []
rpm_url_group_1 = []
rpm_url_group_2 = []
rpm_url_group_3 = [] for index in range(len(rpm_url_list)): if index % 4 == 0:
rpm_url_group_0.append(rpm_url_list[index]) elif index % 4 == 1:
rpm_url_group_1.append(rpm_url_list[index]) elif index % 4 == 2:
rpm_url_group_2.append(rpm_url_list[index]) elif index % 4 == 3:
rpm_url_group_3.append(rpm_url_list[index])
rpm_url_groups = [rpm_url_group_0, rpm_url_group_1, rpm_url_group_2, rpm_url_group_3] for each_rpm_group in rpm_url_groups:
each_process = multiprocessing.Process(target = multi_thread, args = (each_rpm_group,))
process.append(each_process) for one_process in process:
one_process.start() for one_process in process:
one_process.join()# for each_url in rpm_url_list:# print '*****the %s rpm begin to download *******' %each_url## commands.getoutput('wget %s' %each_url)
def main():
url = 'https://mirrors.ustc.e.cn/centos/7/os/x86_64/Packages/'
url_paas = 'http://mirrors.ustc.e.cn/centos/7.3.1611/paas/x86_64/openshift-origin/'
url_paas2 ='http://mirrors.ustc.e.cn/fedora/development/26/Server/x86_64/os/Packages/u/'

start_time = time.time()
rpm_list = get_rpm_url_list(url_paas) print multi_process(rpm_list) # print multi_thread(rpm_list)
#print multi_process()
# print multi_thread(rpm_list)
# for index in range(len(rpm_list)):
# print 'rpm_url is:', rpm_list[index]
end_time = time.time() print 'the download time is:', end_time - start_timeprint main()123456789101112131415161718

代码的功能主要是这样的:
main()方法中调用get_rpm_url_list(base_url)方法,获取要下载的每个rpm包的具体的url地址。其中base_url即中科大基础的镜像源的地址,比如:http://mirrors.ustc.e.cn/centos/7.3.1611/paas/x86_64/openshift-origin/,这个地址下有几十个rpm包,get_rpm_url_list方法将每个rpm包的url地址拼出来并返回。
multi_process(rpm_url_list)启动多进程方法,在该方法中,会调用多线程方法。该方法启动4个多进程,将上面方法得到的rpm包的url地址进行分组,分成4组,然后每一个组中的rpm包再最后由不同的线程去执行。从而达到了多进程+多线程的配合使用。
代码还有需要改进的地方,比如多进程启动的进程个数和rpm包的url地址分组是硬编码,这个还需要改进,毕竟,不同的机器,适合同时启动的进程个数是不同的。

Ⅳ python线程怎么销毁

可以新建一个线程作为父线程,然后实际工作是在它的一个子线程里面做,父线程循环检测一个变量来决定是否退出。Talk
is
cheap
import
threading
class
TestThread(threading.Thread):
def
__init__(self,
thread_num=0,
timeout=1.0):
super(TestThread,
self).__init__()
self.thread_num
=
thread_num
self.stopped
=
False
self.timeout
=
timeout
def
run(self):
def
target_func():
inp
=
raw_input("Thread
%d:
"
%
self.thread_num)
print('Thread
%s
input
%s'
%
(self.thread_num,
inp))
subthread
=
threading.Thread(target=target_func,
args=())
subthread.setDaemon(True)
subthread.start()
while
not
self.stopped:
subthread.join(self.timeout)
print('Thread
stopped')
def
stop(self):
self.stopped
=
True
def
isStopped(self):
return
self.stopped
thread
=
TestThread()
thread.start()
import
time
print('Main
thread
Wainting')
time.sleep(2)
thread.stop()
thread.join()

Ⅳ 怎么用python 的多线程打印

#encoding=utf-8
importthreading
importtime

threadLock=threading.Lock()
num=0
classtimer(threading.Thread):
def__init__(self,count,interval):
threading.Thread.__init__(self)
self.interval=interval
self.count=count
defrun(self):
globalnum
whileTrue:
#获得锁
threadLock.acquire()
ifnum>=self.count:
#释放锁
threadLock.release()
break
num+=1
print'Threadname:%s,%d'%(self.getName(),num)
#释放锁
threadLock.release()

time.sleep(self.interval)

if__name__=='__main__':
thread1=timer(1000,1)
thread2=timer(1000,1)
thread1.start()
thread2.start()
thread2.join()
thread2.join()

Ⅵ python 怎么实现多线程的

线程也就是轻量级的进程,多线程允许一次执行多个线程,Python是多线程语言,它有一个多线程包,GIL也就是全局解释器锁,以确保一次执行单个线程,一个线程保存GIL并在将其传递给下一个线程之前执行一些操作,也就产生了并行执行的错觉。

Ⅶ python 多线程

python支持多线程效果还不错,很多方面都用到了python 多线程的知识,我前段时间用python 多线程写了个处理生产者和消费者的问题,把代码贴出来给你看下:
#encoding=utf-8
import threading
import random
import time
from Queue import Queue

class Procer(threading.Thread):

def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue

def run(self):
for i in range(20):
print self.getName(),'adding',i,'to queue'
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'

# Consumer thread

class Consumer(threading.Thread):

def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue

def run(self):

for i in range(20):
print self.getName(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'

# Main thread

def main():

queue = Queue()
procer = Procer('Procer', queue)
consumer = Consumer('Consumer', queue)
print 'Starting threads ...'
procer.start()
consumer.start()
procer.join()
consumer.join()
print 'All threads have terminated.'
if __name__ == '__main__':
main()

如果你想要了解更多的python 多线程知识可以点下面的参考资料的地址,希望对有帮助!

Ⅷ python threading 一定要 join 吗

Join的作用是众所周知的,阻塞进程直到线程执行完毕。通用的做法是我们启动一批线程,最后join这些线程结束,例如:

foriinrange(10):
t=ThreadTest(i)
thread_arr.append(t)

foriinrange(10):
thread_arr[i].start()

foriinrange(10):
thread_arr[i].join()


此处join的原理就是依次检验线程池中的线程是否结束,没有结束就阻塞直到线程结束,如果结束则跳转执行下一个线程的join函数。


而py的join函数还有一个特殊的功能就是可以设置超时,如下:

Thread.join([timeout])

Wait until the thread terminates. This blocks the calling thread until the thread whosejoin()method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.


也就是通过传给join一个参数来设置超时,也就是超过指定时间join就不在阻塞进程。而在实际应用测试的时候发现并不是所有的线程在超时时间内都结束的,而是顺序执行检验是否在time_out时间内超时,例如,超时时间设置成2s,前面一个线程在没有完成的情况下,后面线程执行join会从上一个线程结束时间起再设置2s的超时。

Ⅸ Python中threading的join和setDaemon的区别及用法

python中得thread的一些机制和C/C++不同:在C/C++中,主线程结束后,其子线程会默认被主线程kill掉。而在python中,主线程结束后,会默认等待子线程结束后,主线程才退出。
python对于thread的管理中有两个函数:join和setDaemon
join:如在一个线程B中调用threada.join(),则threada结束后,线程B才会接着threada.join()往后运行。
setDaemon:主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死,与C/C++中得默认效果是一样的。
#! /usr/bin/env python
import threading
import time
class myThread(threading.Thread):
def __init__(self, threadname):
threading.Thread.__init__(self, name=threadname)
self.st = 2
def run(self):
time.sleep(self.st)
print self.getName()
def setSt(self, t):
self.st = t
def fun1():
t1.start()
print "fun1 done"
def fun2():
t2.start()
print "fun2 done"
t1=myThread("t1")
t2=myThread("t2")
t2.setSt(10);
# t2.setDaemon(True)
fun1()
fun2()
print "now u will see me"

热点内容
脚本故事梗 发布:2024-05-18 18:29:02 浏览:822
安卓和csharp哪个发展好 发布:2024-05-18 18:09:30 浏览:527
换编程题库 发布:2024-05-18 18:00:58 浏览:562
如何使用服务器ip直连网站 发布:2024-05-18 18:00:49 浏览:432
三星n7100哪个安卓版本好用 发布:2024-05-18 17:55:41 浏览:490
万国觉醒采集脚本源码 发布:2024-05-18 17:55:39 浏览:947
sqlserver加字段 发布:2024-05-18 17:54:53 浏览:928
安卓手机如何清除应用记录 发布:2024-05-18 17:31:37 浏览:640
查看存储过程权限 发布:2024-05-18 17:18:33 浏览:192
php类self 发布:2024-05-18 17:15:03 浏览:895