先贴上代码吧,后续再补上文章。。
进程不能用全局变量,因为新进程一启动的就会先把全局变量执行一遍,所以你全局的进程锁是完全没用的,只能传参数传进去
#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()