yield

python协程的理解

十年热恋 提交于 2019-12-19 09:48:57
一、介绍 什么是并发? 并发的本质就是切换+保存状态 cpu正在运行一个任务,会在两种情况下切走去执行其他的任务(切换由操作系统强制控制): 1.任务发生阻塞 2.计算任务时间过长,需要让出cpu给高优先级的程序 协程,又称微线程,是一种用户态的轻量级线程。协程能保留上一次调用时的状态,每次过程重入时,就相当于进入上一次调用的状态,换种说法:进入上一次离开时所处逻辑流的位置,当程序中存在大量不需要CPU的操作时(IO),适用于协程。 协程本质上就是一个线程,以前线程任务的切换是由操作系统控制的,遇到I/O自动切换,现在我们用协程的目的就是较少操作系统切换的开销(开关线程,创建寄存器、堆栈等,在他们之间进行切换等),在我们自己的程序里面来控制任务的切换 进程有三种状态,而线程是进程的执行最小单位,所以也是线程的三种状态 二、协程切换 1.yield是一种在单线程下可以保存任务运行状态的方法 1. yiled 可以保存状态,yield的状态保存与操作系统的保存线程状态很像,但是yield是代码级别控制的,更轻量级 2. send 可以把一个函数的结果传给另外一个函数,以此实现单线程内程序之间的切换 通过yield实现任务切换+保存线程: import time def func1(): for i in range(11): print('func1第%s次打印' % i) time

How to yield empty generator?

…衆ロ難τιáo~ 提交于 2019-12-19 05:17:28
问题 I have a method which takes a generator plus some additional parameters and yields a new generator: function merge(\Generator $carry, array $additional) { foreach ( $carry as $item ) { yield $item; } foreach ( $additional as $item ) { yield $item; } } The usual use case for this function is similar to this: function source() { for ( $i = 0; $i < 3; $i++ ) { yield $i; } } foreach ( merge(source(), [4, 5]) as $item ) { var_dump($item); } But the problem is that sometimes I need to pass empty

Python's PEP 484 type annotation for Generator Expression

≡放荡痞女 提交于 2019-12-19 03:21:45
问题 What is the correct type annotation for a function that returns a generator expression? e.g.: def foo(): return (x*x for x in range(10)) I can't figure out if this is -> Iterator[int] , -> Iterable[int] , -> Generator[int, None, None] , or something else. If there should be one-- and preferably only one --obvious way to do it , then what is the obvious way here? 回答1: All three forms mentioned by you in question are listed as valid alternatives in documentation, Generator expression simply

Scala for-loop. Getting index in consice way

試著忘記壹切 提交于 2019-12-18 13:13:47
问题 In this code I want to increment index to put it to each yield ing result. var index=0 for(str <- splitToStrings(text) ) yield { if (index != 0) index += 1 // but index is equal to `0` all the time new Word(str, UNKNOWN_FORM, index ) } Why I can not change index ? And what the best way to implement this logic then, trying to be concise? 回答1: The zipWithIndex method on most sequence-like collections will give you a zero-based index, incrementing with each element: for ((str, index) <-

Calling coroutines in asyncio.Protocol.data_received

三世轮回 提交于 2019-12-18 13:13:14
问题 I am having a problem doing asynchronous stuff in the asyncio.Protocol.data_received callback of the new Python asyncio module. Consider the following server: class MathServer(asyncio.Protocol): @asyncio.coroutine def slow_sqrt(self, x): yield from asyncio.sleep(1) return math.sqrt(x) def fast_sqrt(self, x): return math.sqrt(x) def connection_made(self, transport): self.transport = transport #@asyncio.coroutine def data_received(self, data): print('data received: {}'.format(data.decode())) x

Pthread - What is the difference between time.h::sleep() and pthread.h::pthread_yield()?

雨燕双飞 提交于 2019-12-18 11:27:00
问题 I spent a good long while looking for info on the differences between time.h::sleep() and pthread.h::pthread_yield() but was unable to find any solid reference material and so I am posting this question. What is the difference between time.h::sleep() and pthread.h::pthread_yield()? Update: The reason I ask is because I was using sleep() to sleep() each individual thread... and my application started having issues when there was 8 threads vs 4 threads. When I went online to see if sleep() only

Caching IEnumerable

ぃ、小莉子 提交于 2019-12-18 11:21:18
问题 public IEnumerable<ModuleData> ListModules() { foreach (XElement m in Source.Descendants("Module")) { yield return new ModuleData(m.Element("ModuleID").Value); } } Initially the above code is great since there is no need to evaluate the entire collection if it is not needed. However, once all the Modules have been enumerated once, it becomes more expensive to repeatedly query the XDocument when there is no change. So, as a performance improvement: public IEnumerable<ModuleData> ListModules()

Splitting textfile into section with special delimiter line - python

故事扮演 提交于 2019-12-18 06:48:34
问题 I have an input file as such: This is a text block start This is the end And this is another with more than one line and another line. The desired task is to read the files by section delimited by some special line, in this case it's an empty line, e.g. [out]: [['This is a text block start', 'This is the end'], ['And this is another','with more than one line', 'and another line.']] I have been getting the desired output by doing so: def per_section(it): """ Read a file and yield sections

js中generator函数的原理和使用

非 Y 不嫁゛ 提交于 2019-12-18 05:02:29
generator又名生成器函数,它是一个崭新的函数类型,它和标准的普通函数完全不同。通过显式的调用生成器函数,能对应的产生一个新的值。通过多次调用后,产生一组值的序列,直到生成器告诉我们无法在产生新的值了。每当生成器函数产生一个新值后,它的执行状态会被保留,直到下次请求到来,它就会从上次离开的位置恢复执行。 1、如何定义generator函数 下面我们来看一个简单的例子: // 通过在function后面添加星号*来定义生成器函数 function* myGenerator() { // 使用关键字yield产生值 yield "first"; yield "second"; yield "third"; } // 生成迭代器gen let gen = myGenerator(); console.log(gen.next()); console.log(gen.next()); console.log(gen.next()); console.log(gen.next()); 上述例子首先定义了一个生成器函数,它能够产生一系列的值。创建生成器函数非常简单,只要在function后面加上一个星号(*)。然后只要在函数体内部使用关键字yield,就能产生值了。 要使用生成器函数,需要先对它进行调用,并生成迭代器gen。 let gen = myGenerator();

The idiomatic way to implement generators (yield) in Golang for recursive functions

梦想与她 提交于 2019-12-17 22:40:06
问题 [ Note: I read Python-style generators in Go, this is not a duplicate of it. ] In Python / Ruby / JavaScript / ECMAScript 6, generator functions could be written using the yield keyword provided by the language. In Go, it could be simulated using a goroutine and a channel. The Code The following code shows how a permutation function (abcd, abdc, acbd, acdb, ..., dcba) could be implemented: // $src/lib/lib.go package lib // private, starts with lowercase "p" func permutateWithChannel(channel