#!/usr/bin/python
#coding=utf-8
# multiprocessing.py
import os
print 'Process (%s) start...' % os.getpid()#getpid是获得当前进程的进程号
pid = os.fork()
#ork()调用一次,返回两次,因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程)
# 然后,分别在父进程和子进程内返回。子进程永远返回0,而父进程返回子进程的ID
print 'pid=',pid
if pid==0:
print 'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())
#getppid()可以拿到父进程的ID
else:
print 'I (%s) just created a child process (%s).' % (os.getpid(), pid)
join:如在一个线程B中调用threada.join(),则threada结束后,线程B才会接着threada.join()往后运行。
setDaemon:主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死,与C/C++中得默认效果是一样的
#!/usr/bin/python
#coding=utf-8
#coding=utf-8
import threading
from time import ctime,sleep
def music(func):
for i in range(2):
print "I was listening to %s. %s" %(func,ctime())
sleep(1)
def move(func):
for i in range(2):
print "I was at the %s! %s" %(func,ctime())
sleep(5)
threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
#当多线程启动的方法的参数只有一个参数的时候,实例化Thread的args的参数要表示为(param1,)需要在参数
#后面打一个逗号,这是因为tuple元组只有一个元素的时候需要在后面加一个逗号,防止歧义。
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
t.join()
print "all
运行结果:
/usr/bin/python2.7 /home/xuhang/otherfiles/xuhang/py/hello.py
I was listening to 爱情买卖. Wed Mar 30 20:39:59 2016
I was at the 阿凡达! Wed Mar 30 20:39:59 2016
I was listening to 爱情买卖. Wed Mar 30 20:40:00 2016
I was at the 阿凡达! Wed Mar 30 20:40:04 2016
all over Wed Mar 30 20:40:09 2016