Threading用于提供线程相关的操做,线程是应用程序中工做的最小单元。python
#!/usr/bin/env python # -*- coding:utf-8 -*- import threading import time def show(arg): time.sleep(1) print 'thread'+str(arg) for i in range(10): t = threading.Thread(target=show, args=(i,)) t.start() print 'main thread stop'
上述代码建立了10个“前台”线程,而后控制器就交给了CPU,CPU根据指定算法进行调度,分片执行指令。算法
更多方法:多线程
1 复制代码 2 import threading 3 import time 4 5 6 class MyThread(threading.Thread): 7 def __init__(self,num): 8 threading.Thread.__init__(self) 9 self.num = num 10 11 def run(self):#定义每一个线程要运行的函数 12 13 print("running on number:%s" %self.num) 14 15 time.sleep(3) 16 17 if __name__ == '__main__': 18 19 t1 = MyThread(1) 20 t2 = MyThread(2) 21 t1.start() 22 t2.start()
线程锁(Lock、RLock)app
因为线程之间是进行随机调度,而且每一个线程可能只执行n条执行以后,当多个线程同时修改同一条数据时可能会出现脏数据,因此,出现了线程锁 - 同一时刻容许一个线程执行操做。socket
1 复制代码 2 #!/usr/bin/env python 3 # -*- coding:utf-8 -*- 4 import threading 5 import time 6 7 gl_num = 0 8 9 def show(arg): 10 global gl_num 11 time.sleep(1) 12 gl_num +=1 13 print gl_num 14 15 for i in range(10): 16 t = threading.Thread(target=show, args=(i,)) 17 t.start() 18 19 print 'main thread stop' 20 复制代码 21 1 22 2 23 3 24 4 25 5 26 6 27 7 28 8 29 9 30 10 31 11 32 12 33 13 34 14 35 15 36 16 37 17 38 18 39 19 40 20 41 21 42 #!/usr/bin/env python 43 #coding:utf-8 44 45 import threading 46 import time 47 48 gl_num = 0 49 50 lock = threading.RLock() 51 52 def Func(): 53 lock.acquire() 54 global gl_num 55 gl_num +=1 56 time.sleep(1) 57 print gl_num 58 lock.release() 59 60 for i in range(10): 61 t = threading.Thread(target=Func) 62 t.start() 63 信号量(Semaphore) 64 65 互斥锁 同时只容许一个线程更改数据,而Semaphore是同时容许必定数量的线程更改数据 ,好比厕全部3个坑,那最多只容许3我的上厕所,后面的人只能等里面有人出来了才能再进去。 66 67 1 68 2 69 3 70 4 71 5 72 6 73 7 74 8 75 9 76 10 77 11 78 12 79 13 80 14 81 15 82 import threading,time 83 84 def run(n): 85 semaphore.acquire() 86 time.sleep(1) 87 print("run the thread: %s" %n) 88 semaphore.release() 89 90 if __name__ == '__main__': 91 92 num= 0 93 semaphore = threading.BoundedSemaphore(5) #最多容许5个线程同时运行 94 for i in range(20): 95 t = threading.Thread(target=run,args=(i,)) 96 t.start()
#!/usr/bin/env python #coding:utf-8 import threading import time gl_num = 0 lock = threading.RLock() def Func(): lock.acquire() global gl_num gl_num +=1 time.sleep(1) print gl_num lock.release() for i in range(10): t = threading.Thread(target=Func) t.start()
Timeride
定时器,指定n秒后执行某操做函数
from threading import Timer def hello(): print("hello, world") t = Timer(1, hello) t.start() # after 1 seconds, "hello, world" will be printed Python 进程
Python 进程ui
from multiprocessing import Process import threading import time def foo(i): print 'say hi',i for i in range(10): p = Process(target=foo,args=(i,)) p.start()
selectspa
#!/usr/bin/env python #-*-coding:utf-8-* import socket,select sk = socket.socket() sk.bind(('127.0.0.1',9999)) sk.listen(5) inputs = [sk,] #sk服务端socket outputs = [] message = {} while True: rlist,wlist,e = select.select(inputs,outputs,[],1) print (len(inputs),len(rlist),len(wlist)) for i in rlist: if i ==sk: conn,addre = i.accept() #conn实际上是socket对象 inputs.append(conn) message[conn] = [] #conn.sendall(bytes('hello',encoding='utf-8')) else: #有人给我发消息了 try: ret = i.recv(1024) if not ret: raise Exception('断开链接') else: outputs.append(i) message[i].append(ret) except Exception as e: inputs.remove(i) del message[i] #全部给我发过消息的人 for w in wlist: msg = message[w].pop() resp = msg + bytes('+response',encoding='utf-8') w.sendall(resp) outputs.remove(w)