doraemon in python threads explained

# ## 9.3 thread (small cost)
 
- A thread is part of the process, each process has at least one thread
 - the process is the smallest unit of computer resource allocation (circle process is responsible for the resource)
 - A thread is a computer CPU scheduling can be minimized unit (a thread is responsible for executing specific code)
 - comparison:
   - process: large overhead data isolation is a resource allocation unit
   - thread: data sharing overhead is a small part of the process of 

# ### 9.3.1 global interpreter lock GIL 

GIL lock:

 - ensure that the entire program in python, only one thread executed by the CPU
 - reason: special garbage collection cpython interpreter
 - GIL lock can not be led parallel threads, can be complicated 

but does not affect the use of threads and high IO type of operation, only have high computational idiom impact on the efficiency of 

# ### 9.3.2 the thread module 

multiprocessing is completely exhibitions threading class writing, using the same basic method 

`` `Python 
# single child thread 
from threading Import the thread

def func():
    print('liujia')
    
Thread(target=func).start()

```

```python
#多个子线程
import os
import time
from threading import Thread

def func(i):
    print('start son thread',i)
    time.sleep(0.2)
    print('end',os.getpid())
    
for i in range(10):
    Thread(target= FUNC, args = . (i,)) Start ()
 Print ( ' main ' ) 
`` ` 

` `` Python 
# the Join method blocks until the child process ends 
DEF FUNC (i):
     Print ( ' Start Son the Thread ' , I) 
    the time.sleep ( 0.2 )
     Print ( ' End ' , os.getpid ()) 
    
T_L = []
 for I in Range (10 ): 
    T = the Thread (target = FUNC, args = (I,)) 
    t.start () 
    t_l.append (t) 
for t inT_L: t.join ()
 Print ( ' child thread is finished ' ) 
    
`` ` 

` `` Python 
# object oriented start thread 
class the MyThread (the Thread):
     DEF  the __init__ (Self, I): 
        self.i = I 
        Super () . the __init__ ()
     DEF RUN (Self):
         Print ( ' Start ' , self.i, self.ident) 
        the time.sleep ( . 1 )
         Print ( ' End ' , self.i) 

for I in Range (10  ):
    T= MyThread(i)
    t.start()
    print(t.ident)
```

```python
#线程里的一些其他方法
from threading import current_thread,enumerate,active_count
def func(i):
    t = current_thread()
    print('start son thread',i,t.ident)
    time.sleep(1)
    print('end son thread',i,os.getpid())

t = Thread(target=func,args=(1,))
t.start()
print(t.ident)
Print(current_thread (). ident)    # skittish in which a thread, current_thread () to get the current thread is this information 
Print (the enumerate ())
 Print (active_count ())    # ===== len (the enumerate ()) 
`` ` 

Note:

 - daemon thread waits until the end of all non-daemon threads will end
 - in addition to the guard outside the main thread code would guard the child thread

 

Guess you like

Origin www.cnblogs.com/doraemon548542/p/11427302.html