线程之间内存是共享的。
使用threading模块实现多线程编程。
import threading
thread_obj = threading.Thread([group [, target [, name[, args [, keyargs]]]]] )
group: 暂时无用,未来功能的预留参数
target: 执行的目标任务名,就是函数的名称
name: 线程名,一般不用设置
args: 以元组的方式给执行任务传参
kwargs: 以字典的方式给执行任务传参
启动线程,让线程开始工作
thread_obj.start()
python
import time
import threading
def sing():
while True:
print("我在唱歌,啦啦啦")
time.sleep(1)
def dance():
while True:
print("我在跳舞,哗哗哗")
time.sleep(1)
thread1 = threading.Thread(target=sing)
thread2 = threading.Thread(target=dance)
thread1.start()
thread2.start()
给线程传参args
python
import time
import threading
def sing(msg):
while True:
print(msg)
time.sleep(1)
def dance(msg):
while True:
print(msg)
time.sleep(1)
thread1 = threading.Thread(target=sing, args=('我在唱歌...',))
thread2 = threading.Thread(target=dance, args=("我在跳舞...",))
thread1.start()
thread2.start()
给线程传参kwargs
python
import time
import threading
def sing(msg):
while True:
print(msg)
time.sleep(1)
def dance(msg):
while True:
print(msg)
time.sleep(1)
thread1 = threading.Thread(target=sing, kwargs={'msg': '我在唱歌'})
thread2 = threading.Thread(target=dance, kwargs={'msg': '我在跳舞'})
thread1.start()
thread2.start()