What is a thread
A thread is the smallest unit of program execution, the process is like an assembly line work.
Open a process: a process of open space in memory, then all the resources of a copy of the data in the primary process, then the calling thread to execute code
Process is resource unit, thread is a unit of execution
VS process two threads
- Open process overhead is very large, much larger than the cost of open thread
- Open thread speed is very fast, faster several times to hundreds of times
- The same process can be shared between threads and thread data, we need the help of the queue and other methods to communicate between processes and processes.
- The main thread and the child thread no separate status of (no primary or secondary), after the end of a main thread to wait for the end of the other sub-thread to the end of the process.
Two ways to open three threads
from threading import Thread
import time
def task(name):
print(f'{name}is running')
time.sleep(1)
print(f'{name}is gone')
if __name__ == '__main__':
t1 = Thread(target=task,args=('大黑',))
t1.start()
print('主线程')
from threading import Thread
import time
class MyThread(Thread):
def __init__(self,name):
super().__init__()
self.name = name
def run(self):
print(f'{self.name}is running')
time.sleep(1)
print(f'{self.name}is gone')
if __name__ == '__main__':
t1 = MyThread('大黑')
t1.start()
print('主进程')
Other methods of four threads
from threading import Thread,currentThread,enumerate,activeCount
import os,time
def task():
print(currentThread())
time.sleep(1)
print('666')
if __name__ == '__main__':
t1 = Thread(target=task,name='线程1')
t2 = Thread(target=task,name='线程2')
t1.start()
t2.start()
time.sleep(2)
print(t1.isAlive()) # 判断线程是否活着
print(t1.getName()) # 获取线程名
t1.setName('子进程1') # 设置线程名
print(t1.getName())
print(currentThread()) # 获取当前线程的对象
print(enumerate()) # 返回一个列表,包含所有的线程对象
print(activeCount()) # 返回正在运行的线程数量
print(f'主线程{os.getpid()}')