线程与进程的介绍

一、先介绍下线程与进程之间的关系:

线程是进程的最小单位,进程里至少有一个线程,这个线程就是主线程。进程就相当于一个程序,是一组资源的集合。

守护线程:守护主线程的,用户start方法之前,当主线程销毁的时候,守护线程跟着一起销毁。

单元测试:就是开发写完功能的时候,自测的代码。开发用什么语言,单元测试就用什么语言。几乎所有语言都要自己单元测试的框架,例如Python里有Unittest、Java里有Junit,PHP里有phpuint。而Unittest里有可以生成测试报告的方法,我们也经常用它来做自动化测试。

下面看一个多进程的例子:

#多进程里又启动多线程
from multiprocessing import Process
import time
import threading
def run_thread():
    time.sleep(60)
    print('%s在运行'%threading.current_thread())

def run():
    for i in range(10):
        t = threading.Thread(target=run_thread)  #这是在起线程。
        t.start()
    # while threading.activeCount() != 1:
    #     pass
    while 1: #这个和上面两行的功能一样,当活跃线程为1的时候,才能通过或者死循环结束。
        if threading.activeCount() == 1:
            break

for i in range(10): #起来了11个进程,有一个主进程。
    p = Process(target=run)  #这个是起进程。
    p.start()


再看一个多线程的例子:

#多线程的例子
import threading
import time,os,glob

def run():
    time.sleep(5)
    print('over!')
start_time = time.time()
print('当前有%s个运行的线程'%threading.activeCount())
for i in range(20):
    t = threading.Thread(target=run)
    t.start()
print('当前有%s个运行的线程'%threading.activeCount())
#threading.activeCount 当前程序有几个线程在活跃。
# while threading.activeCount() != 1:
#     pass
while 1:
    if threading.activeCount() == 1:
        break
print('当前有%s个运行的线程'%threading.activeCount())
end_time = time.time()
print('程序运行时间一共为:run_time:',end_time-start_time)

获取多线程运行函数的返回值:

import requests
import threading

all_res = []
def get_name(name):
    req = requests.get('http://api.nnzhp.cn/api/user/stu_info',
                       params={'stu_name':name})
    res = req.json()
    all_res.append(res)

for i in range(10):
    t = threading.Thread(target=get_name,args=(i,))
    t.start()  #当接口有返回值的时候,怎么取到返回值呢?

while 1:
    if threading.activeCount() == 1:
        break
print(all_res)

守护线程的例子:

import threading
import time

def aaa():
    time.sleep(5)
    print('hhhhhh')

for i in range(10):
    t = threading.Thread(target=aaa)
    t.setDaemon(True) #设置子线程守护主线程,设置之后,就再也不执行aaa方法了。
    t.start()# t.setDaemon(True) #这个必须在start()之前调用

print('全部都死了!') #主线程启动了10个子线程,然后走到最后,10个守护线程就陪葬死了,不执行了。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值