"Python" Asynchronous IO

Source: Internet
Author: User

NO1:

The process appears to be a subroutine, but during execution, it can be interrupted inside the subroutine, then execute another subroutine, and then return to execute at the appropriate time.

Advantage:

1. The greatest advantage is the high implementation efficiency of the process. Because the subroutine switch is not a thread switch, but is controlled by the program itself, therefore, there is no thread switching overhead, and multithreading ratio, the more the number of threads, the performance advantage of the association is more obvious.

2. Do not need a multi-threaded lock mechanism, because there is only one thread, there is no simultaneous write variable conflict, in the process of controlling the shared resources are not locked, only need to determine the state is good, so the execution efficiency is much higher than multithreading.

No2:

Because the co-process is a thread execution, how do you take advantage of multicore CPUs? The simplest method is multi-process + co-progression, which takes full advantage of multicore, and maximizes the high-efficiency of the co-processes, which can achieve very good performance.

Python support for the process is implemented through generator.

defconsumer (): R="'     whiletrue:n=yieldRif  notN:return        Print('[CONSUMER] consuming%s ...'%N) R='OK'defProduce (c): C.send (None) n=0 whileN < 5: N= n + 1Print('[PRODUCER] producing%s ...'%N) R=c.send (n)Print('[PRODUCER] Consumer return:%s'%r) c.close () C=consumer () produce (c)

Run results

consumerA function is one generator that puts an consumer incoming produce post:

    1. First call the c.send(None) startup generator;

    2. Then, once the thing is produced, by c.send(n) switching to consumer execution;

    3. consumerBy yield getting the message, processing, and passing the yield results back;

    4. produceGet consumer The result of processing, continue to produce the next message;

    5. producedecided not to produce, by c.close() closing consumer , the whole process was over.

The entire process is unlocked, executed by a thread, produce and the consumer task is completed collaboratively, so called "co-threads" rather than the thread's preemptive multi-tasking

No3:

"Asyncio"

Importdef  Hello ():    print("Hello world! " )    R=await asyncio.sleep (1)    print("Hello again! " )    Loop=Asyncio.get_event_loop () loop.run_until_complete (hello ()) loop.close ()

Run results

ImportThreadingImportAsyncio@asyncio.coroutinedefHello ():Print('Hello world! (%s)'%Threading.currentthread ())yield  fromAsyncio.sleep (1)    Print('Hello again! (%s)'%threading.currentthread ()) Loop=Asyncio.get_event_loop () Tasks=[Hello (), hello ()]loop.run_until_complete (asyncio.wait (Tasks)) Loop.close ()

Run results

ImportAsyncio@asyncio.coroutinedefwget (host):Print('wget%s ...'%host) Connect=asyncio.open_connection (host,80) Reader,writer=yield  fromConnect Header='get/http/1.0\r\nhost:%s\r\n\r\n'%host Writer.write (Header.encode ('Utf-8'))    yield  fromWriter.drain () whileTrue:line=yield  fromReader.readline ()ifline = = B'\ r \ n':             Break        Print('%s Header >%s'% (Host,line.decode ('Utf-8'). Rstrip ())) Writer.close () Loop=Asyncio.get_event_loop () Tasks=[wget (host) forHostinch['www.sina.com.cn','www.sohu.com','www.163.com']]loop.run_until_complete (asyncio.wait (Tasks)) Loop.close ()

Run results

No4:

Asynchronous operations need to be coroutine done in the pass yield from ;

Multiple coroutine can be encapsulated into a set of tasks and then executed concurrently.

NO5:

asyncAnd await is the new syntax for Coroutine, to use the new syntax, you only need to do a two-step simple replacement:

    1. To @asyncio.coroutine Replace with async ;
    2. yield fromReplace with a await .

NO6:

"Aiohttp"

ImportAsyncio fromAiohttpImportWebasyncdefIndex (Request): Await Asyncio.sleep (0.5)    returnWeb. Response (body=b'', content_type='text/html') AsyncdefHello (Request): Await Asyncio.sleep (0.5) Text=''% request.match_info['name']    returnWeb. Response (Body=text.encode ('Utf-8'), content_type='text/html') Asyncdefinit (Loop): App=web. Application (loop=loop) App.router.add_route ('GET','/', index) App.router.add_route ('GET','/hello/{name}', hello) SRV=await Loop.create_server (App.make_handler (),'127.0.0.1', 8000)    Print('Server started at http://127.0.0.1:8000 ...')    returnSRV loop=Asyncio.get_event_loop () loop.run_until_complete (init (loop)) Loop.run_forever ()

Run results

"Python" Asynchronous IO

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.