laurentluce / python-tutorials Goto Github PK
View Code? Open in Web Editor NEWBlog posts on Python
Blog posts on Python
I want to ask a question. In the producer-consumer with condition program, why there must be a two-layer while in the run() of consumer? I tried to write a consumer run() only with one while like this:
while True: self.condition.acquire( if len(self.integers) == 0: self.condition.wait() integer = self.integers.pop() print integer self.condition.release()
The program will crash for pop an empty list. For count of notify is same as the count of total integers appended to the list, before pop there must be at least one integer in the list, why wait() will return without a notify?
The blog post at http://www.laurentluce.com/posts/python-threads-synchronization-locks-rlocks-semaphores-conditions-events-and-queues/ is often quoted, for example from stack overflow answers.
However, the producer/consumer example using events is flawed and might make people implement this common pattern in a wrong way. The problem is as follows:
It's possible that the producer calls event.set()
and event.clear()
while the consumer is still processing the last integer and thus is not currently waiting for the event. By the time the consumer calls event.wait()
again, the producer's call to event.clear()
may have already completed and the consumer will then wait when it shouldn't, given that there's now an integer ready to be processed. Running the example code as-is multiple times shows this problem: the "xx popped from list" line is sometimes not printed 10 times as it should.
Given that this blog post has quite some exposure, it would make sense to fix this.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.