体会Twisted的异步处理过程

 要学好Twisted,对于掌握其异步处理过程非常重要,以下是描述异步处理的原文:
Trac back: http://twistedmatrix.com/projects/core/documentation/howto/async.html

Asynchronous Programming with Twisted

This document is a introduction to the asynchronous programming model, and to Twisted's Deferred abstraction, which symbolises a 'promised' result and which can pass an eventual result to handler functions.

This document is for readers new to Twisted who are familiar with the Python programming language and, at least conceptually, with core networking conepts such as servers, clients and sockets. This document will give you a high level overview of concurrent programming (interleaving several tasks) and of Twisted's concurrency model: non-blocking code or asynchronous code .

After discussing the concurrency model of which Deferreds are a part, it will introduce the methods of handling results when a function returns a Deferred object.

Introduction to concurrent programming

Many computing tasks take some time to complete, and there are two reasons why a task might take some time:

  1. it is computationally intensive (for example factorising large numbers) and requires a certain amount of CPU time to calculate the answer; or
  2. it is not computationally intensive but has to wait for data to be available to produce a result.

Waiting for answers

A fundamental feature of network programming is that of waiting for data. Imagine you have a function which sends an email summarising some information. This function needs to connect to a remote server, wait for the remote server to reply, check that the remote server can process the email, wait for the reply, send the email, wait for the confirmation, and then disconnect.

Any one of these steps may take a long period of time. Your program might use the simplest of all possible models, in which it actually sits and waits for data to be sent and received, but in this case it has some very obvious and basic limitations: it can't send many emails at once; and in fact it can't do anything else while it is sending an email.

Hence, all but the simplest network programs avoid this model. You can use one of several different models to allow your program to keep doing whatever tasks it has on hand while it is waiting for something to happen before a particular task can continue.

Not waiting on data

There are many ways to write network programs. The main ones are:

  1. handle each connection in a separate operating system process, in which case the operating system will take care of letting other processes run while one is waiting;
  2. handle each connection in a separate thread1 in which the threading framework takes care of letting other threads run while one is waiting; or
  3. use non-blocking system calls to handle all connections in one thread.

Non-blocking calls

The normal model when using the Twisted framework is the third model: non-blocking calls.

When dealing with many connections in one thread, the scheduling is the responsibility of the application, not the operating system, and is usually implemented by calling a registered function when each connection is ready to for reading or writing -- commonly known as asynchronous , event-driven or callback-based programming.

In this model, the earlier email sending function would work something like this:

  1. it calls a connection function to connect to the remote server;
  2. the connection function returns immediately, with the implication that the notify the email sending library will be called when the connect has been made; and
  3. once the connection is made, the connect mechanism notifies the email sending function that the connection is ready.

What advantage does the above sequence have over our original blocking sequence? The advantage is that while the email sending function can't do the next part of its job until the connection is open, the rest of the program can do other tasks, like begin the opening sequence for other email connections. Hence, the entire program is not waiting for the connection.

Callbacks

The typical asynchronous model for alerting an application that some data is ready for it is known as a callback . The application calls a function to request some data, and in this call, it also passes a callback function that should be called when the data is ready with the data as an argument. The callback function should therefore perform whatever tasks it was that the application needed that data for.

In synchonous programming, a function requests data, waits for the data, and then processes it. In asynchronous programming, a function requests the data, and lets the library call the callback function when the data is ready.

Deferreds

Twisted uses the Deferred object to manage the callback sequence. The client application attaches a series of functions to the deferred to be called in order when the results of the asychronous request are available (this series of functions is known as a series of callbacks , or a callback chain ), together with a series of functions to be called if there is an error in the asychronous request (known as a series of errbacks or an errback chain ). The asychronous library code calls the first callback when the result is available, or the first errback when an error occurs, and the Deferred object then hands the results of each callback or errback function to the next function in the chain.

The Problem that Deferreds Solve

It is the second class of concurrency problem — non-computationally intensive tasks that involve an appreciable delay — that Deferreds are designed to help solve. Functions that wait on hard drive access, database access, and network access all fall into this class, although the time delay varies.

Deferreds are designed to enable Twisted programs to wait for data without hanging until that data arrives. They do this by giving a simple management interface for callbacks to libraries and applications. Libraries know that they always make their results available by calling Deferred.callback and errors by calling Deferred.errback . Applications set up result handlers by attaching callbacks and errbacks to deferreds in the order they want them called.

The basic idea behind Deferreds, and other solutions to this problem, is to keep the CPU as active as possible. If one task is waiting on data, rather than have the CPU (and the program!) idle waiting for that data (a process normally called "blocking"), the program performs other operations in the meantime, and waits for some signal that data is ready to be processed before returning to that process.

In Twisted, a function signals to the calling function that it is waiting by returning a Deferred. When the data is available, the program activates the callbacks on that Deferred to process the data.

Deferreds - a signal that data is yet to come

In our email sending example above, a parent function calls a function to connect to the remote server. Asynchrony requires that this connection function return without waiting for the result so that the parent function can do other things. So how does the parent function or its controlling program know that the connection doesn't exist yet, and how does it use the connection once it does exist?

Twisted has an object that signals this situation. When the connection function returns, it signals that the operation is incomplete by returning a twisted.internet.defer.Deferred object.

The Deferred has two purposes. The first is that it says "I am a signal that the result of whatever you wanted me to do is still pending." The second is that you can ask the Deferred to run things when the data does arrive.

Callbacks

The way you tell a Deferred what to do with the data once it arrives is by adding a callback — asking the Deferred to call a function once the data arrives.

One Twisted library function that returns a Deferred is twisted.web.client.getPage . In this example, we call getPage , which returns a Deferred, and we attach a callback to handle the contents of the page once the data is available:

from
 twisted
.web
.client
 import
 getPage


from
 twisted
.internet
 import
 reactor


def
 printContents
(contents
):
    '''
    This is the 'callback' function, added to the Deferred and called by
    it when the promised data is available
    '''


    print
 "The Deferred has called printContents with the following contents:"

    print
 contents


    # Stop the Twisted event handling system -- this is usually handled

    # in higher level ways

    reactor
.stop
()

# call getPage, which returns immediately with a Deferred, promising to

# pass the page contents onto our callbacks when the contents are available

deferred
 = getPage
('http://twistedmatrix.com/'
)

# add a callback to the deferred -- request that it run printContents when

# the page content has been downloaded

deferred
.addCallback
(printContents
)

# Begin the Twisted event handling system to manage the process -- again this

# isn't the usual way to do this

reactor
.run
()

A very common use of Deferreds is to attach two callbacks. The result of the first callback is passed to the second callback:

from
 twisted
.web
.client
 import
 getPage


from
 twisted
.internet
 import
 reactor


def
 lowerCaseContents
(contents
):
    '''
    This is a 'callback' function, added to the Deferred and called by
    it when the promised data is available. It converts all the data to
    lower case
    '''


    return
 contents
.lower
()

def
 printContents
(contents
):
    '''
    This a 'callback' function, added to the Deferred after lowerCaseContents
    and called by it with the results of lowerCaseContents
    '''


    print
 contents

    reactor
.stop
()

deferred
 = getPage
('http://twistedmatrix.com/'
)

# add two callbacks to the deferred -- request that it run lowerCaseContents

# when the page content has been downloaded, and then run printContents with

# the result of lowerCaseContents

deferred
.addCallback
(lowerCaseContents
)
deferred
.addCallback
(printContents
)

reactor
.run
()

Error handling: errbacks

Just as a asynchronous function returns before its result is available, it may also return before it is possible to detect errors: failed connections, erroneous data, protocol errors, and so on. Just as you can add callbacks to a Deferred which it calls when the data you are expecting is available, you can add error handlers ('errbacks') to a Deferred for it to call when an error occurs and it cannot obtain the data:

from
 twisted
.web
.client
 import
 getPage


from
 twisted
.internet
 import
 reactor


def
 errorHandler
(error
):
    '''
    This is an 'errback' function, added to the Deferred which will call
    it in the event of an error
    '''


    # this isn't a very effective handling of the error, we just print it out:

    print
 "An error has occurred: <%s>"
 % str
(error
)
    # and then we stop the entire process:

    reactor
.stop
()

def
 printContents
(contents
):
    '''
    This a 'callback' function, added to the Deferred and called by it with
    the page content
    '''


    print
 contents

    reactor
.stop
()

# We request a page which doesn't exist in order to demonstrate the

# error chain

deferred
 = getPage
('http://twistedmatrix.com/does-not-exist'
)

# add the callback to the Deferred to handle the page content

deferred
.addCallback
(printContents
)

# add the errback to the Deferred to handle any errors

deferred
.addErrback
(errorHandler
)

reactor
.run
()

Conclusion

In this document, you have:

  1. seen why non-trivial network programs need to have some form of concurrency;
  2. learnt that the Twisted framework supports concurrency in the form of asynchronous calls;
  3. learnt that the Twisted framework has Deferred objects that manage callback chains;
  4. seen how the getPage function returns a Deferred object;
  5. attached callbacks and errbacks to that Deferred; and
  6. seen the Deferred's callback chain and errback chain fire.

See also

Since the Deferred abstraction is such a core part of programming with Twisted, there are several other detailed guides to it:

  1. Using Deferreds , a more complete guide to using Deferreds, including Deferred chaining.
  2. Generating Deferreds , a guide to creating Deferreds and firing their callback chains.

Footnotes

  1. There are variations on this method, such as a limited-size pool of threads servicing all connections, which are essentially just optimizations of the same idea.

Index

Version: 8.1.0

看英文文档比较累,但是没办法,只能凑合了。

Matlab中eig内置函数转为C语言 本文记录一下如何将MATLAB中的eig函数转为C语言,即通过C语言求解矩阵的特征值与特征向量。[V,D]=eig(Rx)中V为矩阵Rx的特征向量,D为矩阵的特征值。其中Rx维度为12*12的复矩阵。 首先在MATLAB端创建入口函数保存为eigvalue.m: 打开MATLAB Coder,添加入口函数: 3.在定义输入类型窗口中,需要添加输入数据来训练... 阅读详情

相关推荐

1、电路分析知识全解析:从基础到实践应用

本博客全面解析电路分析知识体系,涵盖从基础的电压、电流、电阻概念到复杂的交流电路、瞬态分析和高级应用如滤波器与变压器等内容。适合电子技术专业学生和技术爱好者学习,提供详细的知识结构、学习路径、实践示例以及丰富的学习资源,括计算机模拟工具Multisim和PSpice的使用指导。通过理论与实践结合,帮助学习者掌握电路分析的核心技能,为电子工程和电力系统等相关领域打下坚实基础。

iii12的专栏 144

PythonTwisted框架上手前所必须了解的异步编程思想

TwistedPython世界中人气最高的framework之一,异步的工作模式使其名扬天下,这里为大家总结了PythonTwisted框架上手前所必须了解的异步编程思想,需要的朋友可以参考下

Python异步网络编程之Twisted框架详解

Twisted 是一个基于 Python 的事件驱动网络框架,专为构建高性能、可扩展的异步网络应用而设计。它自 2002 年发布以来,广泛应用于网络服务器、客户端、协议实现以及分布式系统开发中。其核心优势在于非阻塞 I/O 模型与统一的事件处理机制,使其能够高效处理成千上万的并发连接。与其他网络框架(如 Tornado、asyncio)相比,Twisted 提供了更为丰富的协议支持(如 HTTP、FTP、SMTP 等),并具备跨平台能力。

weixin_32099703的博客 1127

Python异步网络编程框架Twisted使用方法

Twisted是一个Python异步网络编程框架,它可以帮助我们开发高性能的网络应用程序。它提供了一些基本概念,如reactor、protocol、transport和factory等,用于构建高效的网络应用程序。

captain 1270

Twisted 框架简介

Twisted 是一个完整的事件驱动的网络框架,利用它既能使用也能开发完整的异步网络应用程序和协议。它现在还不是标准库的一部分,所以必须单独下载并安装它。使用pip install即可。它提供了大量的支持来建立完整的系统,括网络协议、线程、安全性和身份验证、聊天/ IM、 DBM 及RDBMS 数据库集成、 Web/因特网、电子邮件、命令行参数、 GUI 集成工具等。Twisted 提供了一个更加强大和灵活的框架,并且已经实现了很多协议。可以在。

hubing_hust的专栏 1万+

Python Twisted库:异步网络编程的利器

更多Python学习内容:ipengtao.com在现代网络应用开发中,异步编程已经成为一种必备的技能。Python Twisted库是一款强大的异步网络编程框架,它提供了丰富的工具和功能,使得开发者可以轻松地构建高性能的网络应用。基本概念Twisted库基于事件驱动的编程模型,核心理念是事件循环(Event Loop)和回调机制(Callback)。在Twisted中,所有的网络操作都是非阻塞的...

GitHub_miao的博客 1471

python twisted教程一,异步编程

前言 最近有人在twisted邮件列表中问有没有一个可以让人快速学习twisted的文档.总体的来说:这个系列不是这样的一个文档.如果你没有很多时间或者耐心的话,这个系列的文章不太适合你. 不过,如果你对异步编程了解很少的话,相信一个简短的介绍也不让你完全明白,当然如果你是天才除外.我学习和使用twisted已经好几年了,通过这几年的学习和工作我得出的结论就是:学习twisted困难的地方就是对异...

墨痕诉清风的博客 1303

twisted network programming essentials 读书体会

首先twisted是在python结构下的一个事件驱动的网络框架。你可以在此基础上做出遵循各种协议的client--server结构的软件应用. 刚刚读了第一大章 An Intrduction to twisted主要有如下体会: 1) 所谓的事件驱动是指程序的运行是由外在的因素决定的,比如GUI程序依赖的是用户的鼠标操作,网络程序依赖的是client的送回来的消息,在twisted

Coder 1987

Twisted 入门 教程

From:https://www.cnblogs.com/tomato0906/articles/4678995.html Twisted异步编程入门 系列:http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted stulife 新浪博客 Twisted入门 系列教程:http://blog....

freeking101的博客 2083

python异步框架twisted_PythonTwisted框架上手前所必须了解的异步编程思想

前言最近有人在Twisted邮件列表中提出诸如”为任务紧急的人提供一份Twisted介绍”的需求。值得提前透露的是,这个系列并不会如他们所愿。尤其是介绍Twisted框架和基于Python异步编程而言,可能短时间无法讲清楚。因此,如果你时间紧急,这恐怕不是你想找的资料。我相信如果对异步编程模型一无所知,快速的介绍同样无法让你对其有所理解,至少你得稍微懂点基础知识吧。我已经用Twisted框架几...

weixin_28947385的博客 531

python twisted 核心架构 分析体会

python 的 twisted 异步事件框架功能强大的一塌糊涂,但却也复杂的一塌糊涂;网上的狗屁资源 太垃圾了,基本都没点屁用;对照着手册和api看了2-3遍了,但感觉还是没抓住完整清晰的的骨架;这次为 了彻底掌握 twisted 框架的核心架构,特意边看边记录,最后把核心的流程和一些类画了出来; 下面这个是一些基础类,itransport 是带连接的通道,iudptranspor

IT小小鸟 1020

Python Twisted系列教程1:Twisted理论基础

Twisted简易教程

s_zhchluo的博客 725

python twisted教程_Python Twisted系列教程1:Twisted理论基础

前言:最近有人在Twisted邮件列表中提出诸如”为任务紧急的人提供一份Twisted介绍”的的需求。值得提前透露的是,这个序列并不会如他们所愿.尤其是介绍Twisted框架和基于Python异步编程而言,可能短时间无法讲清楚。因此,如果你时间紧急,这恐怕不是你想找的资料。我相信如果对异步编程模型一无所知,快速的介绍同样无法让你对其有所理解,至少你得稍微懂点基础知识吧。我已经用Twisted框...

weixin_39595271的博客 160

Twisted入门教程(1、2)

Twiested框架是国内著名开源网游框架Firefly的最关键依赖技术。因此,对于这个子框架的深入剖析有助于从内部把握Firefly运行机理。本人从网络上无意间搜索到一个十分优秀的入门教程,尽管有些版本过旧,但是对于我们理解这个框架并无大碍。 Source: http://blog.sina.com.cn/s/blog_704b6af70100py9f.html       1.Twist

LearnboC的博客 581

twisted入门教程之一:Twisted理论基础

前言: 最近有人在Twisted邮件列表中提出诸如”为任务紧急的人提供一份Twisted介绍”的的需求。值得提前透露的是,这个序列并不会如他们所愿.尤其是介绍Twisted框架和基于Python 的异步编程而言,可能短时间无法讲清楚。因此,如果你时间紧急,这恐怕不是你想找的资料。 我相信如果对异步编程模型一无所知,快速的介绍同样无法让你对其有所理解,至少你得稍微懂点基础知识

fangjian1204的专栏 1197

基于Python Unet的医学影像分割系统源码,含皮肤病的数据及皮肤病分割的模型,用户输入图像,模型可以自动分割去皮肤病的区域

基于Python Unet的医学影像分割系统源码,含皮肤病的数据及皮肤病分割的模型,用户输入图像,模型可以自动分割去皮肤病的区域

上一篇: 体会Twisted的异步处理过程
下一篇: Twisted的延时处理机制
pythoner
博客等级 码龄18年 15粉丝 89原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值