进程和线程

共享变量规则:

  空闲让进,忙则等待,有限等待,让权等待。

fork 进程:

 1 #!/usr/bin/env python
 2 #-*-coding:utf-8-*-
 3 
 4 #fork:子进程和父进程之间的交互
 5 #父进程可以检查子进程是否完成,但是无法知道其完成的进度。
 6 
 7 import os
 8 import time
 9 
10 p=os.fork()
11 
12 if p:
13     print os.wait()
14     print "Num"
15 
16     
17 else:
18     time.sleep(3)
19     print "step 1"
20     time.sleep(3)
21     print "step2"
22     exit()
View Code

缺点:如果我想用子进程获得一段数据,返回给父进程

如:

 1 #fork:子进程和父进程之间的交互
 2 #父进程可以检查子进程是否完成,但是无法知道其完成的进度。
 3 
 4 import os
 5 import time
 6 
 7 p=os.fork()
 8 a='test string'
 9 
10 if p:
11     print os.wait()
12     print a
13     print "Num"
14     
15 
16     
17 else:
18     time.sleep(3)
19     a="I'm good students!"
20     print a
21     exit()
View Code

父进程和子进程依赖的不是同一个内存空间。

 subprocess:

 1 import subprocess
 2 import os
 3 import time
 4 
 5 #字符串形式
 6 # rc=subprocess.call(['ls','-l'])
 7 #列表形式
 8 # out = subprocess.call("ls -l", shell=True)
 9 # out = subprocess.call("cd ..", shell=True)
10 
11 #调用系统shell
12 #os.system("ls -l")
13 
14 child = subprocess.Popen(["ping","-c","5","www.google.com"])
15 #父进程执行
16 time.sleep(1)   
17 print  "hello?"
18 
19 #父进程等待子进程结束后执行
20 child.wait()     
21 print("parent process")
22 print child.pid
23 
24 
25 #child.poll()           # 检查子进程状态
26 #child.kill()           # 终止子进程
27 #child.send_signal()    # 向子进程发送信号
28 #child.terminate()      # 终止子进程
View Code

将子进程的结果输出到文本中:

1 import subprocess
2 import os
3 import time
4 
5 fp=open('new.txt','w')
6 out=subprocess.Popen(['ping','-c','5','www.baidu.com'],stdin=subprocess.PIPE,stdout=fp)
7 out.wait()
View Code

将子进程的结果提交给父进程:

1 import subprocess
2 import os
3 import time
4 
5 out=subprocess.Popen(['ping','-c','5','www.baidu.com'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
6 
7 print out.communicate()
View Code

用父进程控制子进程让其等待:

1 import subprocess
2 import os
3 import time
4 
5 import subprocess
6 child = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
7 time.sleep(4)
8 #我们启动子进程之后,cat会等待输入,直到我们用communicate()输入"vamei"。
9 child.communicate("vamei")
View Code

信号量(不太明白):

 1 import signal
 2 # Define signal handler function
 3 def myHandler(signum, frame):
 4     print("Now, it's the time")
 5     exit()
 6 
 7 # register signal.SIGALRM's handler 
 8 signal.signal(signal.SIGALRM, myHandler)
 9 signal.alarm(5)
10 while True:
11     print('not yet')
View Code

 线程:

#!/usr/bin/env python
#!-*-coding:UTF8-*-
from threading import Thread
import time
def func():
    print 'Thread Start:'
    for i in range(10):
        time.sleep(1)
        print i

for i in range(5):
    t=Thread(target=func,name='1')
    t.start()
    t.join() #阻塞线程,此线程结束后才往后执行。
View Code
 1 import threading
 2 import time
 3 import os
 4 
 5 # This function could be any function to do other chores.
 6 def doChore():
 7     time.sleep(0.5)
 8 
 9 # Function for each thread
10 def booth(tid):
11     global i
12     global lock
13     while True:
14         lock.acquire()                # Lock; or wait if other thread is holding the lock
15         if i != 0:
16             i = i - 1                 # Sell tickets
17             print(tid,':now left:',i) # Tickets left
18             doChore()                 # Other critical operations
19         else:
20             print("Thread_id",tid," No more tickets")
21             os._exit(0)              # Exit the whole process immediately
22         lock.release()               # Unblock
23         doChore()                    # Non-critical operations
24 
25 # Start of the main function
26 i    = 100                           # Available ticket number 
27 lock = threading.Lock()              # Lock (i.e., mutex)
28 
29 # Start 10 threads
30 for k in range(10):
31     new_thread = threading.Thread(target=booth,args=(k,))   # Set up thread; target: the callable (function) to be run, args: the argument for the callable 
32     new_thread.start()                                      # run the thread
View Code

线程OPP:

#!/usr/bin/env python
#!-*-coding:UTF8-*-
from threading import Thread
import time
def func():
    print 'Thread Start:'
    for i in range(10):
        time.sleep(1)
        print i

class TestThread(Thread):
    def __init__(self,**kwargs):
        Thread.__init__(self,**kwargs)
        
    def run(self):
        Thread.run(self)

t=TestThread(target=func,name='aa')
t.start()
t.join()
View Code

 线程锁

#!/usr/bin/env python
#!-*-coding:UTF8-*-
import time,threading

class Counter:
    def __init__(self):
        self.value=0
        self.lock=threading.Lock()
    def  increament(self):
        self.lock.acquire()
        self.value=self.value+1
        self.lock.release()
        return self.value

counter=Counter()

class TestThread(threading.Thread):
    def run(self):
        time.sleep(1)
        print counter.increament()
        

         
for i in range(100):
    t=TestThread(None)
    t.start()

print 'haha'
View Code
 1 import threading
 2 import time
 3 import os
 4 
 5 # This function could be any function to do other chores.
 6 def doChore():
 7     time.sleep(0.5)
 8 
 9 # Function for each thread
10 class BoothThread(threading.Thread):
11     def __init__(self,tid,monitor):
12         self.tid=tid
13         self.monitor=monitor
14         threading.Thread.__init__(self)
15     
16     def run(self):
17         while True:
18             monitor['lock'].acquire()
19             if monitor['tick']>0:
20                 print (self.tid,monitor['tick'])
21                 monitor['tick']-=1
22                 
23                 doChore()
24             else:
25                 print "ticket is sell out"
26                 os._exit(0)
27             monitor['lock'].release()
28             doChore()
29         
30         
31 # Start of the main function
32 monitor = {'tick':100, 'lock':threading.Lock()}
33 
34 # Start 10 threads
35 for k in range(10):
36     new_thread= BoothThread(k, monitor)
37     new_thread.start()
38     
View Code
#!/usr/bin/env python
#!-*-coding:UTF8-*-
import time,threading
from _ast import Num
from multiprocessing import Condition

class Goods:
    def __init__(self):
        self.count=6
    def produce(self,num=1):
        self .count=self.count+num
        print "生产了一个商品",self.count
    def consume(self,num=1):
        if(self.count<0):
            return 
        self.count=self.count-num
        print "消费了一个商品",self.count
       

class Producer(threading.Thread):
    def __init__(self,codition,goods):
        threading.Thread.__init__(self)
        self.goods=goods
        self.condition=codition
    def run(self):
        while True:
            self.condition.acquire()
            goods.produce(1)
            self.condition.notify_all()
            self.condition.release()
            time.sleep(4) #4秒生产一个商品、
            
class Consumer(threading.Thread):
    def __init__(self,condition,goods):
        self.cond=condition
        self.goods=goods
        threading.Thread.__init__(self)    
    def run(self):
        self.cond.acquire()
        if self.goods.count<=0:
            self.cond.wait()
        goods.consume(1)
        self.cond.release()
        time.sleep(1)
        
cond=Condition()
goods=Goods()
producer=Producer(cond,goods)
producer.start()

for i in range(10):
    consumer=Consumer(cond,goods)
    consumer.start()
    consumer.join()

print "end-----"

         
Condition

 简单线程

 1 #!/usr/bin/env python
 2 # !-*-coding:utf-8-*-
 3 import threading
 4 import time
 5 
 6 class MyThread(threading.Thread):
 7     def __init__(self,func,*args):
 8         threading.Thread.__init__(self)
 9         self.func =func
10         self.args = args
11 
12     def run(self):
13         print "starting--------->"
14         self.func(self.args)
15         print "end!!!"
16 
17 def func(a):
18     time.sleep(4)
19     print "ajhaa", a
20 
21 th1 = MyThread(func, "dsfasdfasdf")
22 th1.start()
23 th2 = MyThread(func, "dsfasdfasdf")
24 th2.start()
25 th3 = MyThread(func, "dsfasdfasdf")
26 th3.start()
View Code
原文地址:https://www.cnblogs.com/canbefree/p/3816623.html