一、线程的使用
import threadingdef func(arg): print(arg)t = threading.Thread(target=func,args=(11,))t.start()print(123)
import threadingimport timedef func(arg): time.sleep(arg) print(arg)t1 = threading.Thread(target=func,args=(3,))t1.start()t2 = threading.Thread(target=func,args=(9,))t2.start()print(123)
import threadingimport timedef func(arg): time.sleep(2) print(arg)t1 = threading.Thread(target=func,args=(3,))t1.setDaemon(True)t1.start()t2 = threading.Thread(target=func,args=(9,))t2.setDaemon(True)t2.start()print(123)
import threadingimport timedef func(arg): time.sleep(0.01) print(arg)print('创建子线程t1')t1 = threading.Thread(target=func,args=(3,))t1.start()# 无参数,让主线程在这里等着,等到子线程t1执行完毕,才可以继续往下走。# 有参数,让主线程在这里最多等待n秒,无论是否执行完毕,会继续往下走。t1.join(2)print('创建子线程t2')t2 = threading.Thread(target=func,args=(9,))t2.start()t2.join(2) # 让主线程在这里等着,等到子线程t2执行完毕,才可以继续往下走。print(123)
import threadingdef func(arg): # 获取当前执行该函数的线程的对象 t = threading.current_thread() # 根据当前线程对象获取当前线程名称 name = t.getName() print(name,arg)t1 = threading.Thread(target=func,args=(11,))t1.setName('侯明魏')t1.start()t2 = threading.Thread(target=func,args=(22,))t2.setName('刘宁钱')t2.start()print(123)
import threading# 先打印:11?123?def func(arg): print(arg)t1 = threading.Thread(target=func,args=(11,))t1.start()# start 是开始运行线程吗?不是# start 告诉cpu,我已经准备就绪,你可以调度我了。print(123)
import threading# 多线程方式:1 (常见)def func(arg): print(arg)t1 = threading.Thread(target=func,args=(11,))t1.start()# 多线程方式:2class MyThread(threading.Thread): def run(self): print(11111,self._args,self._kwargs)t1 = MyThread(args=(11,))t1.start()t2 = MyThread(args=(22,))t2.start()print('end')
二、多线程
import threadingv1 = [11,22,33] # +1v2 = [44,55,66] # 100def func(data,plus): for i in range(len(data)): data[i] = data[i] + plust1 = threading.Thread(target=func,args=(v1,1))t1.start()t2 = threading.Thread(target=func,args=(v2,100))t2.start()
import threadingimport requestsimport uuidurl_list = [ 'https://www3.autoimg.cn/newsdfs/g28/M05/F9/98/120x90_0_autohomecar__ChsEnluQmUmARAhAAAFES6mpmTM281.jpg', 'https://www2.autoimg.cn/newsdfs/g28/M09/FC/06/120x90_0_autohomecar__ChcCR1uQlD6AT4P3AAGRMJX7834274.jpg', 'https://www2.autoimg.cn/newsdfs/g3/M00/C6/A9/120x90_0_autohomecar__ChsEkVuPsdqAQz3zAAEYvWuAspI061.jpg',]def task(url): ret = requests.get(url) file_name = str(uuid.uuid4()) + '.jpg' with open(file_name, mode='wb') as f: f.write(ret.content)for url in url_list: t = threading.Thread(target=task,args=(url,)) t.start()
import timeimport threadinglock = threading.RLock()n = 10def task(i): print('这段代码不加锁',i) lock.acquire() # 加锁,此区域的代码同一时刻只能有一个线程执行 global n print('当前线程',i,'读取到的n值为:',n) n = i time.sleep(1) print('当前线程',i,'修改n值为:',n) lock.release() # 释放锁for i in range(10): t = threading.Thread(target=task,args=(i,)) t.start()