By way of inheritance, implement threads:
import time
from threading import Thread
class MyThread(Thread):
def __init__(self, args):
super().__init__() #执行父类中的__init__()
self.args = args
def run(self):
time.sleep(2)
print(self.args)
t = MyThread(10)
t.start()
Check thread indeed runs in the same process (pid comparison)
import time,os
from threading import Thread
#多线程并发
def func(n):
time.sleep(2)
print('子线程%d:%d'%(n,os.getpid()))
print('主线程:',os.getpid())
for i in range(10):
t = Thread(target=func,args=(i,))
t.start()
Output:
Memory data sharing
Within the same process, the data is shared between multiple threads of.
import time,os
from threading import Thread
#多线程并发
def func(n):
global g
g = 10
print(g,os.getpid())
g = 100
t_list = []
for i in range(5):
t = Thread(target=func,args=(i,))
t.start()
t_list.append(t)
for j in t_list:
j.join()
print(g)
Output:
Global Interpreter Lock (GIL)
In the procedure under Cpython python interpreter, at the same time, multiple threads can have only one thread executed by the CPU.
When running high CPU usage code (computing class) when multiple threads does not dominant, but in general, the code we are running high I / O, so multi-threaded or useful.
GIL added code that only one thread can access the CPU, the lock is 线程
, which is characteristic of Cpython interpreter, Jpython no GIL.(面试)
In a multithreaded environment, Python virtual machine executes the following manner
- Set GIL;
- Switch to a thread to execute;
- A specified number of byte code instructions or thread initiative to the control;
- The county is set to sleep;
- Unlock GIL;
- Repeat the above steps
When calling external code (C / C ++ extension functions) of, GIL will be locked, know so far (during which no due Python bytecode is run, it will not do a thread switch), write an extension of the end of the function programmers can take the initiative to unlock the GIL.
Multithreading efficiency
import time
from threading import Thread
from multiprocessing import Process
def func(n):
n + 1
if __name__ == '__main__':
t_list = []
start = time.time()
for i in range(100):
t = Thread(target=func,args=(i,))
t.start()
t_list.append(t)
for t in t_list:
t.join()
t1 = time.time() - start
t_list = []
start = time.time()
for i in range(100):
t = Process(target=func,args=(i,))
t.start()
t_list.append(t)
for t in t_list:
t.join()
t2 = time.time() - start
print(t1,t2)
Multi-threaded socket server
client end
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',8080))
msg = sk.recv(1024).decode('utf-8')
print(msg)
inp = input('>>>').encode('utf-8')
sk.send(inp)
sk.close()
end server
import socket
from threading import Thread
def chat(conn):
conn.send(b'hello')
msg = conn.recv(1024).decode('utf-8')
print(msg)
conn.close()
sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()
while True:
conn,addr = sk.accept()
Thread(target=chat,args=(conn,)).start()
sk.close()
Thread some other method
threading.current_thread()
All information for the current thread's
threading.get_ident()
current thread thread number
threading.active_count()
of how many threads are
threading.enumerate()
all threads that are currently
import threading,time
def nihao(n):
time.sleep(1)
print(n, threading.current_thread(), threading.get_ident())
for i in range(10):
threading.Thread(target=nihao, args=(1,)).start()
print(threading.active_count())
print(threading.current_thread())
print(threading.enumerate())
Output: