python学习(二):并行开发(线程和进程)

  
         多进程

        linux、unix平台专属


        fork
        wait
        Waitpid
        pipe和singal
        守护进程
        
pipe和singal进程间管道通信、wait
Waitpid
#!/usr/bin/python27
#
import os
import time
import signal
def onsingal_term(a,b):
    print "over"
signal.signal(signal.SIGTERM,onsingal_term)
def myfork():
    r,w = os.pipe()
    a=1
    pid = os.fork()
    if pid==0:
        os.close(r)
        w=os.fdopen(w,'w')
        print "this is child.%d--%d" %(pid,os.getpid())
        time.sleep(1)
        #print a+1
        while True:
            a=a+1
            if a>100:
                os.kill(os.getppid, signal.SIGTERM)
            w.write(str(a))
            print a
        w.close()
    else:
        os.close(w)
        r=os.fdopen(r)
        print r.read()
        r.close()
        #status = os.waitpid(pid,1)
        print "this is parent.%d--%d" %(pid,os.getpid())
        #time.sleep(2)
        #status = os.waitpid(pid,0)
        print a+3
        status = os.waitpid(pid,1)
        #time.sleep(4)
if __name__ == '__main__':
    myfork()
    
守护进程:    
#!/usr/bin/python27
#
import os
import sys

def daemon_test():
    pid = os.fork()
    if pid > 0:
        sys.exit(0)
    os.setsid()
    os.umask(0)

    pid = os.fork()
    if pid>0:
        sys.exit(0)
    f=open('text.txt', 'w')
    a=1
    while True:
        a=a+1
        f.write(str(a))
    f.close()
if __name__ == '__main__':
    daemon_test()
    
    多线程:
    
        #!/usr/bin/python27
#
import thread
import time
c=1
def fun(no,a):
    time.sleep(1)
    global c
    while True:
        c=c+1
        print 'thread no %d = %d,' %(no,c)

def test():
    thread.start_new_thread(fun,(1,2))
    thread.start_new_thread(fun,(2,2))
    time.sleep(4)
   #thread.start_new_thread(fun,(1,2))
if __name__ == '__main__':
    test()    


网上例子:wait
Waitpid

    #coding=UTF-8
    import os
    import time
    def myfork():
        a = 1
        pid = os.fork()
        if pid == 0:
            print "this is child %d--%d %d" %(pid, os.getpid(), os.getppid())
            time.sleep(1)
            print a+1
            #while True:
            #    pass
        else:
            status = os.waitpid(pid, 0)   ##将此行注释,比较执行结果
            #status = os.waitpid(pid. 1)
            print "this is parent %d--%d %d" %(pid, os.getpid(), os.getppid())
            print a+3
    if __name__ == '__main__' :
        myfork()

pipe和singal

进程间管道通信

    #coding=UTF-8
    import os
    import time
    def onsignal_term(a, b):
        print 'over'
    signal.signal(signal.SIGTERM,onsignal_term)  #将终端信号注入到系统信号中
    def myfork():
        r, w = os.pipe()
        a = 1
        pid = os.fork()
        if pid == 0:
            os.close(r)
            w = os.write(w, 'w')
            print "this is child %d--%d %d" %(pid, os.getpid(), os.getppid())
            while True:
                a = a+1
                if a>100:
                    os.kill(os.getppid, signal.SIGTERM)
                os.write(w,str(a))
                #w.write(a)
                print '/n'
            w.close()
        else:
            os.close(w)
            r = os.fdopen(r)
            print r.read()
            r.close()
            print "this is parent %d--%d %d" %(pid, os.getpid(), os.getppid())
            status = os.waitpid(pid, 1)
    if __name__ == '__main__' :
        myfork()

守护进程

守护进程方式

    #coding=UTF-8
    import os
    import sys
    def daemon_test():
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
        os.setsid()    #脱离终端
        os.umask(0)
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
        f = open('test.txt', 'w')
        a =1
        while True:
            a=a+1
            f.write(str(a))
        f.close()
    if __name__=='__main__':
        daemon_test()

运行结果:

    ls -lh   //-rw-rw-rw-.  1 root root 171M May 29 01:29 test.txt
    tail -f test.txt
    ps -ef daemon
    kill *****   //杀死守护进程

多线程开发

 Thread

    import thread
    import time
    def funt(no, a):
        while True:
            a =a+1
            print 'Thread no %d = %d, '%(no, a)
    def test():
        thread.start_new_thread(funt, (1,2))
        thread.start_new_thread(funt, (2,2))
        time.sleep(20)   #注释看看结果,父进程会立即回收,派生的两个子线程马上就会被回收
    if __name__=='__main__':
        test()

 共享变量与临界资源:多线程操作全局变量

    import thread
    import time
    c=1
    def funt(no, a):
        global c  
        while True:
            time.sleep(1)
            c =c+1
            print 'Thread no %d = %d, '%(no, c)
    def test():
        thread.start_new_thread(funt, (1,2))
        thread.start_new_thread(funt, (2,2))
        time.sleep(20)
    if __name__=='__main__':
        test()

 Threading 面向对象编程
定义一个单线程类

    #coding=UTF-8
    import threading
    import time
    count = 0
    class aa(threading.Thread):  #aa由thread对象继承而来
        def __init__(self, no, interval): #构造函数
            threading.Thread.__init__(self) #初始化基类的构造函数
            self.no = no
            self.interval = interval
            self.isstop = False
        def run(self):       #重载方法
            global count
            while not self.isstop:
                count+=1
                print 'thread %d = %d' % (self.no, count)
                time.sleep(self.interval)
        def stop(self):
            self.isstop = True
    def factory():
        t1 = aa(1,1)
        t1.start()
        time.sleep(20)
        t1.stop()
    if __name__=="__main__":
        factory()

 锁机制:多线程加锁操作

    #coding=UTF-8
    import threading
    import time
    mylock = threading.RLock()  #读锁
    count = 0
    class aa(threading.Thread):  #aa由thread对象继承而来
        def __init__(self, no, interval): #构造函数
            threading.Thread.__init__(self) #初始化基类的构造函数
            self.no = no
            self.interval = interval
            self.isstop = False
        def run(self):       #重载方法
            global count
            a =0
            while a<10:
                mylock.acquire()
                count+=1
                mylock.release()
                print 'thread %d = %d' % (self.no, count)
                #time.sleep(self.interval)
                a+=1
        def stop(self):
            self.isstop = True
    def factory():
        t1 = aa(1,1)
        t1.start()
        t2 = aa(2,2)
        t2.start()
        time.sleep(20)
        t1.stop()
        t2.stop()
    if __name__=="__main__":
        factory()   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值