Python (6)

Source: Internet
Author: User

Multithreaded development

1, Threading. Thread module

start

getname (): Get Name

SetName (): Set name

Isdaemon ()

Setdaemon ()

Join (Timeout): a process, such as the time of a thread, such as timeout equals 5 is executed to the thread when the process and other threads for 5 seconds, if the thread executes more than 5 seconds do not wait, continue to execute the process

Run ()

2. Multithreading Development Create Threads

Code: From threading Import Threaddef Foo (ARG): Print ARGT1 = Thread (target=foo,args= (1,)) T1.start () Results: 1

3, producer-consumer model (about the concept in the previous blog has been written)

Code 1#!/usr/bin/env python# -*- coding: utf-8 -*-import threadingimport  timeimport randomimport queue  #队列模块def  producer (name,que):  #生产者      while true:        que.put (' bun ')   #相当于把包子放到仓库里          print  '%s: Made a bun '  %name  #打印出做了一个包子出来          time.sleep (Random.randrange (5))    #厨师5秒内做出一个包子def  consumer ( Name,que):  #消费者     while True:          try:                        #异常处理, if there is no steamed buns to eat just wait for the chef to make buns              que.get_nowait ()                  print ‘ %s: Ate a bun '  %name        except Exception:             print u ' no buns '          time.sleep (Random.randrange (3))   #消费者3秒内吃掉一个包子q  = queue.queue ()   #队列p1  =  threading. Thread (target=producer,args=[' chef 1 ', Q])    #目标是Producer这个函数, args is a reference p2 = threading. Thread (target=producer,args=[' Chef 2 ', Q]) P1.start () P2.start () c1 = threading. Thread (target=consumer,args=[' Zhang San ', Q]) c2 = threading. Thread (target=consumer,args=[' John Doe ', Q]) C1.start () C2.start ()

4. Thread process

(1) Difference:

• One process produces multiple threads

• Threads are shared memory, processes are independent

• Threads are mostly service-to-process and cannot be run alone

5. Thread Lock

The lock object is a low-level programming tool provided in Python

Lock.acquire () Get a lock

Lock.release () Release a lock

#!/usr/bin/env python#coding:utf-8 Import threadingimport Time Gl_num = 0 lock = Threading.     Lock () def Func (): Lock.acquire () global gl_num gl_num +=1 time.sleep (1) Print Gl_num lock.release () For I in range: T = Threading. Thread (Target=func) T.start ()

5. Inter-thread communication threading.event

Python provides the event object for inter-thread communication, which is a signal flag set by the thread, and if the signal flag bit is true, other threads wait until the signal touches.

The event object implements a simple threading mechanism that provides the setup signal, clears the signal, waits, and so on to implement the communication between threads.

1. Setting the Signal

Use the Set () method of the event to set the signal token inside the event object to be true. The event object provides the Isset () method to determine the state of its internal signal flag. When you use the Event object's set () method, the IsSet () method returns the true

2 Clear signal

Use the Clear () method of the event to clear the signal flag inside the event object and set it to false, and when the clear method of the event is used, the IsSet () method returns a false

3 Waiting

  using the event's Wait ()

Code:#!/usr/bin/env python# -*- coding: utf-8 -*-import threadingimport   timedef prodecer ():     print u ' chef: wait for someone to buy steamed buns   #先打印这句      event.wait ()     #打印完上一句就等待consumer线程把False变成True     event.clear ()    #然后清除状态     print u ' chef: Someone came to buy steamed buns '   #如果consumer把False变成True, just print this sentence      print  ' Chef: I'm making buns for you '    #在打印这一句          Time.sleep (5)    #停5秒钟     print  chef: Steamed bun come on, take it   # When printing this sentence, turn false to True and tell another thread     event.set () Def consumer ():     Print u ' Zhang San: go buy a bun to eat '      event.set ()   #把False变成True告诉producer线程      time.sleep (2)     print  ' Zhang San: wait for the bun to be done '     while true :         if event.isset ():            print   ' Thanks '             break         else:            print   ' Zhang San: All Right,             time.sleep (1) event= Threading. Event () p1 = threading. Thread (Target=prodecer) c1 = threading. Thread (Target=consumer) P1.start () C1.start () Results: Cook: Wait for someone to buy steamed buns Zhang San: to buy a steamed bun to eat the chef: someone to buy steamed buns Chef: I'm making buns for you Zhang San: wait for the bun to do Zhang San: ok Zhang San: Okay, Zhang San: All right, Chef: bun, come on, take it. Thanks

5. Host Management: Paramiko

Paramiko is a python-based SSH2 remote secure connection that supports authentication and key methods. Can implement remote command execution, file transfer, intermediate SSH proxy and other functions, relative to Pexpect, the package of higher level, closer to the function of SSH protocol.

Installation:

Python-develyum-y Install Python-devel pycrypto:https://www.dlitz.net/pub/dlitz/crypto/pycrypto/ PYCRYPTO-2.6.TAR.GZTAR-ZXVF pycrypto-2.6.tar.gzcd pycrypto-2.6/python setup.py build && python setup.py Install test:python>> Import Cryptoecdsa:wget https://pypi.python.org/packages/source/e/ecdsa/ ECDSA-0.13.TAR.GZ#MD5=1F60EDA9CB5C46722856DB41A3AE6670TAR-ZXVF ecdsa-0.13.tar.gzpython setup.py Install Paramiko: wget https://github.com/paramiko/paramiko/archive/v1.12.2.tar.gztar-zxvf v1.12.2.tar.gz CD Paramiko-1.12.2/python setup.py build && python setup.py install test:python>> import paramikocrypto Error: ' Module ' object has no att Ribute ' have_decl_mpz_powm_sec ' If this error is reported please install Python-devel











This article is from the "Ming python" blog, so be sure to keep this source http://pythonzhai.blog.51cto.com/10391994/1745803

Python (6)

Related Article

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.