Python concurrent Programming: multithreading-two ways to turn on threads

Source: Internet
Author: User

Introduction of a threading module

The Multiprocess module completely imitates the interface of the threading module, which has a great similarity in the use level.

Two ways to open a thread

Way One

From threading Import Threadimport timedef Sayhi (name):    time.sleep (2)    print ("%s say hello"% name) if __name__ = = ' __main__ ':    t = Thread (Target=sayhi, args= (' Mike '))    T.start ()    print ("Main thread")

Way Two

From threading Import Threadimport Timeclass Sayhi (Thread):    def __init__ (self, name):        super (). __init__ ()        Self.name = name    def run (self):        time.sleep (2)        print ('%s say hello '% self.name) if __name__ = = ' __main__ ': 
   t = Sayhi (' Mike ')    T.start ()    print ("Main thread")

  

Three exercises

1, multi-threaded implementation of the concurrent socket communication

Client:

From socket import *ip = ' 127.0.0.1 ' port = 8081c = Socket (af_inet, Sock_stream) c.connect ((IP, port)) while True:    msg = Input ("Please enter the client's information"). Strip ()    if not msg:        continue    c.send (Msg.encode (' Utf-8 '))    data = C.RECV (1024    print ("Message Received:", Data.decode (' Utf-8 '))

  

Service side:

From socket Import *from threading import Threaddef Talk (conn): While    True:        try:            data = CONN.RECV (1204)            If not data:                break            Conn.send (Data.upper ())        except Connectionreseterror:            break    conn.close () def Server (IP, port):    server_socket = socket (af_inet, sock_stream)    server_socket.bind ((IP, port))    Server_ Socket.listen (1)    while True:        conn, addr = server_socket.accept ()        p = Thread (Target=talk, args= (conn,))        P.start ()    conn.close () if __name__ = = ' __main__ ':    server (' 127.0.0.1 ', 8081)

Python concurrent Programming: multithreading-two ways to turn on threads

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.