加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python一个文件里面多个函数同时执行(多进程的方法,并发)

发布时间:2020-12-20 10:50:13 所属栏目:Python 来源:网络整理
导读:#coding=utf-8 import time from selenium import webdriver import threading def fun1(a): print a def fun2(): print 222 threads = [] threads.append(threading.Thread(target=fun1,args=(u‘爱情买卖‘,))) threads.append(threading.Thread(target=fu

#coding=utf-8
import time
from selenium import webdriver
import threading

def fun1(a):
  print a

def fun2():
  print 222

threads = []
threads.append(threading.Thread(target=fun1,args=(u‘爱情买卖‘,)))
threads.append(threading.Thread(target=fun2))
print(threads)
if __name__ == ‘__main__‘:
  for t in threads:
    t.setDaemon(True) #我拿来做selenium自动化模拟多个用户使用浏览器的时候,加了这个就启动不了,要去掉
    t.start()

?

import threading

首先导入threading 模块,这是使用多线程的前提。

threads = []

t1 = threading.Thread(target=fun1,))

threads.append(t1)

创建了threads数组,创建线程t1,使用threading.Thread()方法,在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。

接着以同样的方式创建线程t2,并把t2也装到threads数组。

for t in threads:
  t.setDaemon(True)
  t.start()

最后通过for循环遍历数组。(数组被装载了t1和t2两个线程)

setDaemon()

setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。

start()

开始线程活动。

?

参考:?

https://www.cnblogs.com/xxswkl/p/11110728.html

https://www.cnblogs.com/fnng/p/3670789.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读