1. 程式人生 > >多程序同步問題,python多程序解讀

多程序同步問題,python多程序解讀

先貼上程式碼吧,後續再補上文章。。

程序不能用全域性變數,因為新程序一啟動的就會先把全域性變數執行一遍,所以你全域性的程序鎖是完全沒用的,只能傳引數傳進去

#coding=utf-8

#
#測試一個程序在寫檔案的時候,另外一個檔案能不讀
#
import multiprocessing,time


"""
測試結果,with 的鎖對程序完全沒用  只對執行緒有用
"""




#執行緒可以用全域性變數,但是程序用全域性變數完全沒有,所有的全域性變數都是有自己的一份
#拷貝在裡面,完全無法控制
#thread_lock = multiprocessing.Semaphore(1)  
#thread_lock = threading.Lock()
def read(thread_lock):
  thread_lock.acquire()
  with open("rw-test.txt","r") as f:
    print "in read"
  #thread_lock.acquire()
  #print "in read"
  #thread_lock.release()
    
def write(thread_lock):
  thread_lock.acquire()
  with open("rw-test.txt","r") as f:
    print "in write"
  
  #thread_lock.acquire()
  #print "in write"
  #while True:
  #  1+1
  #print "write end"
  #thread_lock.release()
    
if __name__ == "__main__":    


  #thread_lock = multiprocessing.Lock()


  thread_lock = multiprocessing.Semaphore(1)  
  r = multiprocessing.Process(target=read,args=(thread_lock,))
  w = multiprocessing.Process(target=write,args=(thread_lock,))
  w.start()
  time.sleep(1)
  r.start()
  w.join()
  r.join()