toggle it, or it will return its parent co-process. In Gevent, when a process is finished running, it automatically dispatches those unfinished processes. import gevent import socket urls = [ " www.baidu.com ", " www.gevent.org ", " www.python.org " ]jobs = [ Gevent.spawn (socket.gethostbyname, url) for URL In Urls]gevent.joinall (jobs, timeout =5 print [job.value for job in Jobs] We obtain the IP address of three websites by the ass
1. The meaning and realization of the association ProcessThe co-process is a scheduling mechanism of the transcendental function of single-session single-thread, which is dispatched by certain dispatching means.(Python uses the generator mechanism, Greenlet uses assembly control to point to the program).2. What is the role of the co-processThe computer is divided into IO bound and CPU bound two types of tas
First, the introduction of the co-process.The coprocessor, also known as a micro-thread, is single-process, single-threaded, but in some cases, the execution of the threads in Python is more efficient than multi-threading.This is because the transitions between the processes and the threads are completely different! The switch of the process is controlled by the program itself (the developer of the program uses yield to control, the switch between the
mutually exclusive lock of the enhanced version, a lock can control multiple thread access, lock, you can only let a thread access, semaphore can control the number.#Specify the release of severalnum=10deffunc (l,i):GlobalNUM L.acquire ()#lockedNum-=1Time.sleep (2) Print(Num,i) l.release ()#UnlockLock=threading. Boundedsemaphore (5)#Lock 5 Threads forIinchRange (15): T=threading. Thread (target=func,args=(Lock,i)) T.start ()#the results displayed505 35 25) 11 405080607-4 9-5 13-5 10-5 11-5 1
Similarly, a common reference to a Count object Base.count = 0 when the class attribute count is changed, the instance property count also changes to print (A1.count) # 0 classbase:count= 0def__init__ (self): Base.count+=1defoutput (self): print (Self.count) a1=base () a2=base () a3=base () print (Base.count) #3a1.count=9 This instance property is detached from the class attribute base.count+=4 Therefore, the change in the class attribute count does not affect the instance properties Countprint
Preface: Diagram of Threads and processes
From the point of view, in each application execution process, will produce a master process and the main thread to complete the work, when we need concurrent execution, it will be through the main process to generate a series of sub-processes (and then through the child process to produce a series of child threads) to make different CPU calls, so as to achieve the concurrency effect. However, it is important to note that in general, each process is inde
. ,It should be emphasized that:# 1. Python threads are at the kernel level, that is, scheduled by the operating system control (such as single-threaded encounters IO or too long execution time will be forced to hand over the CPU execution permissions, switch other threads run)#2. Single-wire range opening process, once IO is encountered, The switch is controlled from the application level (not the operating system) to increase efficiency (!!!) Non-IO
, wait until all the tasks in the pool have been completed and the resources have been reclaimed before continuing Wait=false, returns immediately, and does not wait for the task in the pool to complete Submit and map must be before shutdown 4.result Getting Results ret.result () 5. Callback function Add_done_callback (back) The parameter that is received inside the callback function is an object that needs to get the return value through result Executing in
asynchronous association, the use of single process and multi-process will take a lot of time, we have to test:First, test the time of the single process:It can be seen that multiprocessing is more efficient than a single thread.3.7 Integration with multiple processesSince asynchronous and multi-process have promoted network requests, why not combine them? On the latest Pycon 2018, John Reese from Facebook introduced the features of Asyncio and multi
Reference: http://www.cnblogs.com/Eva-J/articles/8324673.htmlintroduction of co-processCo-process: is a single-threaded concurrency, also known as micro-threading, fiber. English name Coroutine. One sentence describes what a thread is: The process is a lightweight thread of user-state, that is, the process is scheduled by the user program itself. ,It should be emphasized that:#1. The python thread is at the kernel level, which is the #2 that is contro
First: Co-processPreliminary understanding of the co-processdefEater ():Print('start to eat') whileTrue:food=yield Print('is eating food:%s'%Food )defproducer (): Dog=Eater () Next (dog)#The next wake-up process function #then the following actions are all Dog.send (values)food1='Beijing Roast Duck'food2='shredded pork with fish flavor'dog.send (FOOD1) dog.send (FOOD2) producer () output: start to eat iseating food: Beijing roast Duck isEating food: shredded pork with fish flavorSe
() db_cursor.execute (, id) result=db_cursor.fetchone () []
r.zadd (, Id,result) e: %e
db_cursor.close () : () result= (Result) (% (Id,result))###Zadd: commands are used to add one or more member elements and their sub-values to an ordered setZscore: The command returns an ordered set of members in the key score. Returns nil if the member does not exist in the sorted collection, or if the key does not exist. This article is from the "DBSpace" blog, so be sure to keep this source http:
: Crawlerfromgeventimportmonkey;monkey.patch_all()importgeventimportrequestsimporttimedefget_page(url): print(‘GET: %s‘%url) response=requests.get(url) ifresponse.status_code ==200: print(‘%d bytes received from %s‘%(len(response.text),url))start_time=time.time()gevent.joinall([ gevent.spawn(get_page,‘https://www.python.org/‘), gevent.spawn(get_page,‘https://www.yahoo.com/‘), gevent.spawn(get_page,‘https://github.com/‘),])stop_time=time.time()print(‘run time is %s‘%(stop_time-start_time))协程应用:
Foreplay: Understand the next queue queues before you make a custom thread poolThe queue can hold the underlying data type, or it can hold special data types such as classes, objects, etc. fromQueue Import Queueclasst:def __init__ (self,num): Self.num=num def printf (self): print (Self.num,id (self.num))if__name__ = ="__main__": Queue= Queue (0) Num= A queue.put (num) #可以存放基础数据类型t=T (num) queue.put (t) #可以存放对象CLS=T queue.put (CLS) #可以存放类DT= Queue.Get() print (ID (dt), dt,type (DT)) #1385649280
","UID": Str (res[0]),"Ukey": res[1]}Response = Self.client.put ("/customers/customer_state",headers=headers). Text # Client.get () is used to refer to the requested path, which can be added headers,params,body parameters;Assert ' success ' in response@task (1)def get_member_account_withdrawal_details (self):"" "to obtain the member account withdrawal details" "res = Self.get_headers ()headers = {"Channel": "Shop","UID": Str (res[0]),"Ukey": res[1]}params = {"Page": "10","Size": "10"}Response =
Introduction to the scope rules and closures in Python, and introduction to python
Before performing a simple analysis on the closures in Python, let's take a look at the scope rules in Python. For details about the scope in
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.