您的位置:首页 > 编程语言 > Python开发

python进程&线程

2015-11-05 10:18 621 查看
# -*- coding:UTF-8 -*-
'''
Created on 2015年10月25日

@author: young
'''

import os
import threading
import time
print '多进程创建'
print 'Process (%s) start...' % os.getpid()
s=1111;
pid = os.fork()
if pid==0:
s=222
print 'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())

else:
s=333
print 'I (%s) just created a child process (%s).' % (os.getpid(), pid)

print s

print '创建跨平台的多进程'
from multiprocessing import Process
import os

#子进程要执行的代码'
def run_proc(name):
print 'Run child process %s (%s)...' % (name, os.getpid())

print 'Parent process %s.' % os.getpid()
p = Process(target=run_proc, args=('test',))
print 'Process will start.'
p.start()
p.join()
print 'Process end.'

print '###########多线程#################'
def task():
print "%s is running "% (threading.current_thread().name,)
for i in range(5):
print "%s --> %d"%(threading.current_thread().name,i)

time.sleep(1)#暂停1秒

print "%s end..." % (threading.current_thread().name,)

print "%s is running "% (threading.current_thread().name,)
th=threading.Thread(target=task,name="new thread")

th.start()
th.join()#加入到主线程中,等子线程结束后再结束主线程
print "%s end..." % (threading.current_thread().name,)

print '###################'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python