python线程任务run_python线程、进程知识梳理
一.python線程
線程用于提供線程相關的操作,線程是應用程序中工作的最小單元。
#!/ usr / bin / env python
# - * - coding:utf-8 - * -
import threading
import time
def show(arg):
time.sleep(1)print'thread
'+ str(arg)
for我在范圍(10)中:
t = threading.Thread(target = show,args =(i,))
t.start()print'main
thread stop
上述代碼創建了10個“前臺”線程,然后控制器就交給了CPU,CPU根據指定算法進行調度,分片執行指令。
更多方法:
start線程準備就緒,等待CPU調度
setName為線程設置名稱
getName獲取線程名稱
setDaemon設置為后臺線程或前臺線程(默認)
如果是后臺線程,主線程執行過程中,后臺線程也在進行,主線程執行完畢后,后臺線程不論成功與否,均停止
如果是前臺線程,主線程執行過程中,前臺線程也在進行,主線程執行完畢后,等待前臺線程也執行完成后,程序停止加入逐個執行每個線程,執行完畢后繼續往下執行,該方法使得多線程變得無意義,run線程被執行cpu調度后自動執行線程對象的運行方法
import threading
import time
class MyThread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num
def run(self):#定義每個線程要運行的函數
print("running on number:%s" %self.num)
time.sleep(3)
if __name__ == '__main__':
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
自定義線程類
二.線程鎖(鎖,RLOCK)
由于線程之間是進行隨機調度,并且每個線程可能只執行n條執行之后,當多個線程同時修改同一條數據時可能會出現臟數據,所以,出現了線程鎖 - 同一時刻允許一個線程執行操作。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time
gl_num = 0
def show(arg):
global gl_num
time.sleep(1)
gl_num +=1
print gl_num
for i in range(10):
t = threading.Thread(target=show, args=(i,))
t.start()
print 'main thread stop'
未使用鎖
互斥鎖同時只允許一個線程更改數據,而Semaphore是同時允許一定數量的線程更改數據,比如廁所有3個坑,那最多只允許3個人上廁所,后面的人只能等里面有人出來了才能再進去。
三.信號量(信號量)
import threading,time
def run(n):
semaphore.acquire()
time.sleep(1)
print("run the thread:%s" %n)
semaphore.release()
if __name__ == '__main__':
num= 0
semaphore = threading.BoundedSemaphore(5) #最多允許5個線程同時運行
for i in range(20):
t = threading.Thread(target=run,args=(i,))
t.start()
四.事件(事件)
python線程的事件用于主線程控制其他線程的執行,事件主要提供了三個方法set,wait,clear。
事件處理的機制:全局定義了一個“Flag”,如果“Flag”值為False,那么當程序執行event.wait方法時就會阻塞,如果“Flag”值為True,那么event.wait方法時便不再阻塞。
clear:將“Flag”設置為False
set:將“Flag”設置為True
def condition_func():
ret = False
inp = input('>>>')
if inp == '1':
ret = True
return ret
def run(n):
con.acquire()
con.wait_for(condition_func)
print("run the thread:%s" %n)
con.release()
if __name__ == '__main__':
con = threading.Condition()
for i in range(10):
t = threading.Thread(target=run, args=(i,))
t.start()
六.Timer
七.python進程
八.進程數據共享
進程各自持有一份數據,默認無法共享數據
#!/usr/bin/env python
#coding:utf-8
from multiprocessing import Process
from multiprocessing import Manager
import time
li = []
def foo(i):
li.append(i)
print 'say hi',li
for i in range(10):
p = Process(target=foo,args=(i,))
p.start()
print 'ending',li
進程間默認無法數據共享
'c': ctypes.c_char, 'u': ctypes.c_wchar,
'b': ctypes.c_byte, 'B': ctypes.c_ubyte,
'h': ctypes.c_short, 'H': ctypes.c_ushort,
'i': ctypes.c_int, 'I': ctypes.c_uint,
'l': ctypes.c_long, 'L': ctypes.c_ulong,
'f': ctypes.c_float, 'd': ctypes.c_double
類型對應表
from multiprocessing import Process, Queue
def f(i,q):
print(i,q.get())
if __name__ == '__main__':
q = Queue()
q.put("h1")
q.put("h2")
q.put("h3")
for i in range(10):
p = Process(target=f, args=(i,q,))
p.start()
Code
當創建進程時(非使用時),共享數據會被拿到子進程中,當進程中執行完畢后,再賦值給原值。
九.進程池
進程池內部維護一個進程序列,當使用時,則去進程池中獲取一個進程,如果進程池序列中沒有可供使用的進進程,那么程序就會等待,直到進程池中有可用進程為止。
進程池中有兩個方法:
申請
apply_async
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from multiprocessing import Process,Pool
import time
def Foo(i):
time.sleep(2)
return i+100
def Bar(arg):
print arg
pool = Pool(5)
#print pool.apply(Foo,(1,))
#print pool.apply_async(func =Foo, args=(1,)).get()
for i in range(10):
pool.apply_async(func=Foo, args=(i,),callback=Bar)
print 'end'
pool.close()
pool.join()#進程池中進程執行完畢后再關閉,如果注釋,那么程序直接關閉
總結
以上是生活随笔為你收集整理的python线程任务run_python线程、进程知识梳理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: junit跳过datasource_ma
- 下一篇: 并行算法 Parallel Algori