Chapter 15, concurrent programming of thread

Chapter 15, concurrent programming of thread

1. What is the thread

Correct concept: the process is actually not a unit of execution, the process is a resource unit, comes with a thread in each process, thread execution unit is on cpu

Abstract understanding:

Process refers to an application running on the system; thread is the basic unit of the system processor time allocation of resources, or a separate unit within the process of execution. To the operating system, which is the thread scheduling unit.

线程:cpu最小的执行单位
进程:资源集合/资源单位.
线程运行 = 运行代码
进程运行 = 各种资源 + 线程

Pictures understand:

175-è¿ ?? C ?? ???? çº¿ç¨ å ç ?? å ?? ???? ?? ºa "- 01.png

Examples understand:

在传统操作系统中,每个进程有一个地址空间,而且默认就有一个控制线程
在工厂中,  每个车间都有房子,而且每个车间默认就有一条流水线.

2. The difference between processes and threads

  1. Thread: single thread of memory space shared data (data in the process)

  2. Process: the physical memory space isolation (more process memory space isolated from each other)

  3. It tells the operating system to open up the process memory space

    A thread is tells the operating system to perform a task code (create threads is 100 times the speed of the process)

3. Open thread in two ways

Function open

from threading import Thread
import time
def task(name):
    print('%s is runing '%name)
    time.sleep(2)
    print('%s is done'%name)
 
t=Thread(target=task,args=('子线程',))
t.start()

Open class

class Task(Thread): 
    def run(self): 
    print('%s is runing ' % self.name) 
    time.sleep(2)   
    print('%s is done' % self.name)
t = Task()t.start()print('zhu')

4. Create a sub-thread of the child process speed

from threading import Thread
from multiprocessing import Process
import time

def task(name):
    print(f'{name} is running')
    time.sleep(2)
    print(f'{name} is end')


if __name__ == '__main__':
    t = Thread(target=task,args=('子线程',))
    p = Process(target=task,args=('子进程',))
    # t.start()
    p.start()
    print('主')
------------------------------------------------
############开启子线程的打印效果:################

子线程 is running
主
子线程 is end

##########开启子进程打印效果:##################

主
子进程 is running
子进程 is end

Summary: Thread faster than process creation

5. proof of child threads share data

from threading  import Thread
import time,os

x = 100
def task():
    global x
    x = 50
    print(os.getpid()) # 4652
    
if __name__ == '__main__':

    t = Thread(target=task)
    t.start()
    time.sleep(2)
    print(x) # 50
    print(os.getpid()) # 4652
------------------------------------------
4652
50
4652

Open process is opening up new child process memory space, and the thread opener thread is a shared memory space

Namely: pid number of the process to open the child is not the same,

Open thread pid chant the same thread

6. Thread join method

Single child thread

子线程 start
主线程
子线程 endfrom threading import Thread
import time
def task():
    print('子线程 start')
    time.sleep(2)
    print('子线程 end')
def task2():
    print('子线程 start')
    time.sleep(5)
    print('子线程 end')

t = Thread(target=task)
t.start()
t2.start()
t.join() # 等待子线程运行结束
print('主线程')
-------------------------------
子线程 start
子线程 end
主线程
----------------------------------
#给t.join()加注释的结果如下
子线程 start
主线程
子线程 end

Description: The main thread will wait for the start sleep child threads and such a time, the child thread () before join, indicating that the child thread must run over, only to run print('主线程'), only the main thread is finished, if given t.join () add a comment, then the main thread is finished, the main thread ends directly.

Multiple child threads

from threading import Thread
import time
def task(name,n):
    print(f'{name} start')
    time.sleep(n)
    print(f'{name} end')

t1 = Thread(target=task,args=('线程1',1))
t2 = Thread(target=task,args=('线程2',2))
t3 = Thread(target=task,args=('线程3',3))
start = time.time()
t1.start()
t2.start()
t3.start()
t1.join() # 111s
t2.join() #
t3.join()
end = time.time()
------------------------------------------
线程1 start
线程2 start
线程3 start
线程1 end
线程2 end
线程3 end
3.0022878646850586
#主线程开始->线程1开始->线程1结束->线程2开始->线程2结束->线程3开始->线程3结束->主线程结束
#因为1线程、2线程、3线程进入了同一个方法,本应该"同时"start()运行,但是现在是线程1 在start后使用join,那么线程2会老老实实的等线程1先跑完

Description: implements concurrent execution of multiple threads

Think

Think about how the use of multiple threads in the case of a single cpu core?

A: The multi-threaded program that runs on a single core CPU, the same time only one thread running, the system switches to help you thread it, the system allocation of time slices to each thread to execute each time slice is probably about 10ms, looks like to run simultaneously, but each thread is actually running a little change to the other threads continue to run will not improve the efficiency of switching threads actually increase spending

7. Understand the process join

from multiprocessing import Process
from threading import Thread
import time
def task():
    print('进程 开启')
    time.sleep(10)
    print('进程 结束')
def task2():
    print('子线程 开启')
    time.sleep(2)
    print('子线程 结束')

if __name__ == '__main__':
    p = Process(target=task)
    t = Thread(target=task2)
    t.start() # 开线程
    p.start() # 开进程
    print('子进程join开始')
    p.join() # 主进程的主线程等待子进程运行结束
    print('主') 

8. Other Relevant usage thread

   # print(t1.is_alive()) # True
   # print(t1.getName()) # Thread-1
   # print(t2.getName()) # Thread-2
   # t1.setName('班长')
   # print(t1.getName())
   # print(currentThread().name)
   # print(enumerate()) # [<_MainThread(MainThread, started 1856)>, <Thread(Thread-1, started 6948)>, <Thread(Thread-2, started 3128)>]
   # print(activeCount()) # 3
   # print(len(enumerate())) # 3

Guess you like

Origin www.cnblogs.com/demiao/p/11536044.html