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

668次阅读
没有评论
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=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,args=(u'爱情买卖',))

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

开始线程活动。

后记:

搞了个并发浏览器操作,

如果要做参数化,用ddt会导致所有行为都在一个浏览器操作,去掉ddt框架后,并发正常

参考: 

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

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

转载于:https://www.cnblogs.com/kaibindirver/p/11432880.html

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python基础教程2022-11-22发表,共计1094字。
新手QQ群:570568346,欢迎进群讨论 Python51学习