Python多线程简单使用

版权声明:多多交流。 https://blog.csdn.net/qq_42776455/article/details/83019274

Python多线程编程

大家查Python多线程资料时,应该会发现很多说Python的多线程是伪多线程。其实是那其他语言的多线程对比了如:C#。如果你的并发量密集这句话毫无疑问是对的,而且效果相差很明显,但如果你只是少量线程来说其实也没差。入坑的话推荐菜鸟教程:http://www.runoob.com/python/python-multithreading.html

写在前面

多线程早先接触过,不过也只是去做了个,walk,talk,walk,talk…这样的小案例,做过一个简单的多线程爬虫。今天拿到了一个proxy_pool,想在爬取的过程中动态的从proxy_pool中取对应的代理ip,这时我想到了多线程也顺便回顾下以前的知识。

创建简单的多线程

threading.Thread类创建线程对象(import threading)

  1. 函数无参:
    target参数的值对应的是函数名。
    def talk():
    	pass
    thread = threading.Thread(target=talk)
    thread.start()
    
  2. 函数有参(一个或多个)
    target参数后,添加需要传入函数中的参数
    def speak(a,b):
    	pass
    thread = threading.Thread(target=speak,('shuo','hua'))
    

多线程入门小案例

import threading,time

def walk():
    for i in range(5):
        print('walk')
        time.sleep(1)

def listen():
    for i in range(5):
        print('listen to music')
        time.sleep(1)
# 创建两个线程
thread_1 = threading.Thread(target=walk)
thread_2 = threading.Thread(target=listen)
# 执行的线程
thread_1.start()
thread_2.start()

运行结果:

walk
listen to music
walk
listen to music
walk
listen to music
walk
listen to music
listen to music
walk

setDaemon()设置守护线程

setDaemon默认为False,意味着当多线程运行时主线程结束,但有没结束的线程继续运行。当setDaemon参数设置为True时,主线程结束,所有线程不过有没有执行完,都一起结束执行。

setDaemon()在线程开始运行前设置为True,将walk的循环次数改为100。

import threading,time

def walk():
    for i in range(100):
        print('walk')
        time.sleep(1)

def listen():
    for i in range(5):
        print('listen to music')
        time.sleep(1)

thread_1 = threading.Thread(target=walk)
thread_2 = threading.Thread(target=listen)

thread_1.setDaemon(True)

thread_1.start()
thread_2.start()

设置为守护线程的本应执行100次,可随着主线程结束,守护线程也跟着结束。

walk
listen to music
walk
listen to music
walk
listen to music
walk
listen to music
walk
listen to music
walk
Process finished with exit code 0

join()等待线程执行完毕

如果只从字面意思理解,就是把当前线程加入到主线程中,更通俗点说就是主线程需要等待子线程执行完成之后再结束。
需要在线程启动后,才可使用join。

import threading,time

def walk():
    for i in range(100):
        print('walk')
        time.sleep(1)

def listen():
    for i in range(5):
        print('listen to music')
        time.sleep(1)

thread_1 = threading.Thread(target=walk)
thread_2 = threading.Thread(target=listen)

thread_1.start()
thread_2.start()
thread_1.join()

walk会执行100次以后,整个程序才会结束。

walk
listen to music
walk
listen to music
walk
listen to music
walk
listen to music
walk
listen to music
walk
walk
walk
...

猜你喜欢

转载自blog.csdn.net/qq_42776455/article/details/83019274