Python——单线程与多线程

并发:一个人吃,一口菜一口包子,但由于切换速度快,感觉像在同时吃菜和包子
并行:两个人同时吃,一个人吃包子,一个吃菜,所有吃包子和吃菜是同时的。

同步:并发或并行的各个任务不是独自运行的任务之间有一定的交替顺序,
           可能在运行完成一个任务结果后,另一个任务才会开始运行。
          (接力赛跑,要拿到接力棒之后下个选手才会开始运行)
异步:并发或并行的各个任务可以独立运行,一个任务的运行不受另一个
          任务影响。
          (各个选手在不同的赛道比赛一样,跑步速度不受其他赛道选手的影响)

多进程爬虫是并发的方式执行,通过进程的快速切换加快网络爬虫的速度。
为了数据安全所做的决定设置有GIL(GLobal Interpreter Lock)全局解锁器。
在Python中,一个线程的执行过程包括获取GIL,执行代码直到挂起和释放GIL。

import requests
import time

link_list = []
with open ("C:/Users/Administrator/Desktop/alexa.txt") as file:
     file_list = file.readlines()
     for eachone in file_list:
          link = eachone.split('\t')[1]
          link = link.replace('\n','')
          link_list.append(link)

start = time.time()
for eachone in link_list:
     try:
          r = requests.get(eachone)
          print(r.status_code, eachone)
     except Exception as e:
          print('Error:  ', e)
end = time.time()
print('串行的总时间:  ', end-start)
'''python多线程的两种方法
'1、函数式:调用_thread模块中的start_new_thread()函数产生新线程
'2、类包装式:调用Thread库创建线程,从threading.Thread继承'''

import  _thread
import time

#为线程定义一个函数
def print_time(threadName, delay):
     count = 0
     while count<3:
          time.sleep(delay)
          count+=1
          print(threadName, time.ctime())

_thread.start_new_thread(print_time,("Thread-1",1))  #新线程
_thread.start_new_thread(print_time,("Thread-2",2))  #新线程
print("Main Finished")   #主线程

'''
_thread中使用start_new_thread()函数产生新线程
语法:_thread.start_new_thread(function, args[, kwargs])
其中,function表示线程函数, 在上例中为print_time; args为传递给线程函数
的参数,必须是tuple(元祖)类型,在上例中为("Thread-1",1);最后的kwargs
是可选参数。

_thread提供了低级别,原始的线程,它相比于threading模块,功能比较单一有限
threading模块则提供了Thread类来处理线程。'''

在这里插入图片描述

import threading
import time

class myThread(threading.Thread):
     def __init__(self, name, delay):
          threading.Thread.__init__(self)
          self.name = name
          self.delay = delay

     def run(self):
          print("Starting "+self.name)
          print_time(self.name, self.delay)
          print("Exiting" +self.name)

def print_time(threadName, delay):
     counter = 0
     while counter <3:
          time.sleep(delay)
          print(threadName, time.ctime())
          counter +=1


'''
过程解说:
1、将任务手动地分到两个线程中,即thread1 = myThread("Thread-1",1)
2、然后在myThread这个类中对线程进行设置,使用run()表示线程运行的方法,
      当counter小
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值