码迷,mamicode.com
首页 > 编程语言 > 详细

python---进程、线程

时间:2016-07-23 21:01:48      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

一、进程

 

 

 

二、线程

 

1,使用Thread方法创建线程

技术分享
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = zhoufeng

import threading
import time

def f1(arg):
    time.sleep(5)
    print(arg)

t=threading.Thread(target=f1,args=(123,))  #target表示让线程干什么活,args是参数
t.start()   #线程进入准备状态,等待CPU调度
print(end)

‘‘‘
输出如下:
end
123
‘‘‘

#主线程执行到最后了  但程序未退出,在等待子程序执行完
View Code

 

2,主线程默认是等待子线程执行完毕后再退出的,也可以通过setDaemon方法设置成主线程不等待子线程

技术分享
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = zhoufeng

import threading
import time

def f1(arg):
    time.sleep(5)
    print(arg)

t=threading.Thread(target=f1,args=(123,))  #target表示让线程干什么活,args是参数
t.setDaemon(True)   #设置主线程不等子线程
t.start()   #线程进入准备状态,等待CPU调度
print(end)

‘‘‘
输出如下:
end
‘‘‘

#主线程执行完后就退出了
View Code

 

 

3,前面的setDaemon方法只能决定等不等待子线程执行完,更为灵活的join方法能指定在什么位置等待,最多等待多久(即便子进程未执行完也继续往下执行)

技术分享
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = zhoufeng

import threading
import time

def f1(arg):
    time.sleep(5)
    print(arg)

t=threading.Thread(target=f1,args=(123,))  
t.setDaemon(True)   
t.start()   
t.join(2)   #表示主线程执行到这里暂停,等待子进程执行,最多等待2秒

print(end)

‘‘‘
输出如下:
end
‘‘‘
#在本例中无法等待子进程执行完毕,子进程耗时5秒,而主进程只会等待2秒
#join方法和setDaemon方法不冲突
View Code

 

python---进程、线程

标签:

原文地址:http://www.cnblogs.com/zhoufeng1989/p/5698785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!