I get that this guide tries to ease you in into low level concurrency concepts.
However, if you try to just get work done in Python, this is not what you want.
Don't do threads/processes yourself, use pools:
import random
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
def hello():
seconds = random.randint(0, 5)
print(f"Start blocking for {seconds}s")
time.sleep(seconds)
print(f"Stopped blocking after {seconds}s")
return seconds
if __name__ == "__main__":
with ProcessPoolExecutor(max_workers=2) as exec:
a = exec.submit(hello)
b = exec.submit(hello)
for future in as_completed((a, b)):
print(future.result())
And don't manage the loop yourself. Use Python 3.7, and replace:
I agree with you. We should use a reliable library, as you said. The primary purpose of this article is to help people understand what a coroutine and an event loop are. Therefore, programmers can use asyncio API fluently without misuse.
However, I don't think use threads/processes is a bad idea. A pool gives you a constrain to utilize threads/processes, but sometime we may want to adjust the number of threads/processes based on system load. Under this circumstance, using a pool is not the best choice.
You’re sending the poor newbie on a journey of self-discovering of picklable-non-picklable, passing of arguments back and forth, working with Queues (which have well-known yet undocumented race conditions), missing exception stack traces due to dead processes and all sorts of useless garbage they don’t need to know about.
Also what exactly would that newbie be building that starts and stops threads depending on the system load? What kind of a contraption is that? What are you doing?
Finallizing all of the above: under the circumstance you mentioned, you should check whether you have just seriously over-architected the solution.
I understand you are worried about newbies misuse APIs. You remind me that I should add a warning to inform the sample code in this article should not use in programs. Thanks.
Also, I did not advocate a newbie should start and stop threads by themselves. I want to say I agree that we should use high-level APIs in most cases, but, in some cases, we may need to use low-level APIs to achieve our missions. I am unwilling to limit what kind of APIs should use. In my opinion, like you said: "you have just seriously over-architected the solution," we should be careful to use APIs. Even though high-level APIs are safer, programmers may misuse them.
I think this is not an excellent solution. You have to wait for all threads finish. I agree that we should use high-level API in most of the time, but, in some cases, we still need low-level APIs to support us to reach some goals.
import random
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
def hello():
seconds = random.randint(0, 5)
print(f"Start blocking for {seconds}s")
time.sleep(seconds)
print(f"Stopped blocking after {seconds}s")
return seconds
if __name__ == "__main__":
with ProcessPoolExecutor(max_workers=2) as exec:
a = exec.submit(hello)
b = exec.submit(hello)
for future in as_completed((a, b)):
print(future.result())
The same exact same API exist for thread BTW. I don't think a tutorial should introduce you to concurrency using manual process/thread management any more. I makes no sense to me.
You may note that multiprocessing still eats more RAM than with typical Go/Rust code since max_workers=n means n+1 Python VM spawing but on modern servers you don't really feel it. That's what most WSGI setup do anyway.
Now, before 2019, there was one more use case that wasn't served well: how do you share some computation between isolated processes that need to communicate to make their work ? Typical use case was people using numpy or pandas crunching numbers that depended on each others. Indeed, communicating between processing using piping is expensive given the cost of message passing serialization.
from multiprocessing.managers import SharedMemoryManager
with SharedMemoryManager() as smm:
sl = smm.ShareableList(name="unique_name", range(2000))
The sl object can then contain int, float, bool, str, bytes and None and its reference can be shared among processes. Each item can be deleted and replaced. You an also get an hold on sl by using the "unique_name" if you don't have the reference at hand.
There is a raw ShareableMemory object for stuff like numpy/pandas array buffers if this is your main concern.
Thank you for this. I did not know of this change in implementation in Python 3.8.
Are you a core dev btw? I have a complaint about single threads and processes and how they have absolutely no way to return values back to the main thread except through some shared memory object. Am I too ignorant to understand how big of a challenge it is to do this?
Instead to implement this, I keep having to use like single process pools that already have return mechanisms encoded. All I need is for a way of starting off a thread (or process) and joining it once my main thread / process is done and retrieving its return value for my use (assuming there is one).
For very simple use cases, you can inherit from Thread and force join() to return the value:
class SimpleReturningThread(Thread):
result = None
def run(self):
try:
if self._target:
self.result = self._target(*self._args, **self._kwargs)
finally:
del self._target, self._args, self._kwargs
def join(self, *args, **kwargs):
super().join(*args, **kwargs)
return self.result
Personally, I'd stick to using a pool with only one worker in it. It's not worth the trouble of doing all this work. Wrap it in a few functions if you do the same thing repeatedly and call it a day, it's unlikely going to be what most your code is about anyway.
Correct me if I'm wrong, but from what you've said I take it that the GIL issue has not been resolved (i.e. the Python interpreter is not thread-safe, Python still can't have a single process, with a single Python interpreter, running multiple CPU-bound threads all doing useful compute in Python, running against a single unified local memory space containing all of the objects, as you would in say C or C++). The only option is to resort to more elaborate schemes involving multiple processes, multiple interpreters, and explicitly managed shared memory windows -- but all of these options are in place now, so there is at least a solution to most common use cases, even if it's not as simple as in other languages with proper support for threads and shared local memory.
Linkedin used to trick people into thinking you have to pay to see someones profile when you can see it just fine by logging out. That is not against Googles policy. Not sure if they still do that, but I used the logout trick a lot a few years ago.
You sure about that? How big qualifies as big in your eyes? Medium implemented homepage cloaking in November of 2019 and within a month they lost 40% of their overall search visibility:
Pinterest? Google is somehow able to crawl images on their site, but I certainly can't view these images without creating an account and logging in. Their site ranks highly enough that I gave up on google image search last year.
Additionally, off the top of my head Bloomberg and NYT both won't allow me to view more than a few articles but let the Google crawler index their articles.
I've definitely seen article text on Google that was not presented to me when I clicked the link, and not because the article was updated or something, but because I was blocked from seeing the article.
There are many cases where what you need is instant soup powder, not home made velouté.
And this will save me from writing tests for those lines. With all major browsers. And documentation. And maintain all that, of course, for the next 5 years.
And when new devs will arrive in the team to provide the training for the custom code. I may even not be here anymore
So yes, it can be overkill, or just what you need.
E.G: some server side dev need a quick fix for his personal web site.
Besides, even a lib with zero tests like this one will have enough users and tickets open that it will be better tested that the server side dev code that don't know JS much.
The problem is, there’s no way to enforce this. If you are a CA, there is nothing technically stopping you from issuing a certificate for google.com. There’s no infrastructure for the ability to say “this CA is valid only for sites that agree with the risks involved in using it”.
Actually, I believe there are. IIRC it's possible for a CA's root cert to be limited to only a certain TLD. There's an extension called "Name Constraints" that limits a Root SSL Cert, and I believe it is honored by chrome.
It's an optional extension, so a client may ignore it without failing the connection. It needs a lot more adoption. I could, for example, instead of getting a wildcard cert, get LE to sign a CA valid for my domain. That way I can issue certs for my domain myself and put load off of LE.
Only if the certificate authority doesn't implement a way of not submitting their cert to the CT log servers. Of course, eventually someone might notice (if the certificate is used widely enough - if it's used to attack specific known people, maybe not) and realise that a certificate is being served that doesn't have corresponding CT info, but browsers don't check that.
The ct-policy link you gave and that section of RFC 6962 are about SCTs. The existence of the Signed Certificate Timestamp does not prove the certificate was actually logged, it just proves that the Log promises to log this certificate within the Maximum Merge Delay (24 hours in the case of the Web PKI). A log might in fact be lying or have suffered a grave technical problem.
Figuring out how best to have browsers check the logs are truly accurate while preserving user privacy (e.g. obviously if you call a log to ask "Did you log this certificate for clown-porn.example ?" it gives them a good idea about your taste in circus-related adult content which you probably don't want them to have) is an ongoing topic of research.
With SCT checks you're in very good shape already today - bad guys would need to compromise several distinct entities to successfully pull this off. It's just not quite "Fire and forget" safe yet.
If the certificate wasn't submitted to an otherwise trustworthy CT log server then there's no way to provide an SCT ("Signed Certificate Timestamp") for a qualified CT log server. Some browsers (including Chrome and Safari) expect to be shown qualified SCTs for certificates issued after a certain date.
The SCT is signed by the log, so if you want them to lie you'd need to control enough logs to get enough qualified SCTs. Bad news, for Chrome that means it must include a Google log, which means now you're asking Google to conspire against themselves.
For now you could sidestep this by issuing bogus certificates with back-dated issuance dates. But that will stop working once those dates are too long ago for a certificate to still be valid. I think that happens some point later this year or in 2021 maybe? If you show Chrome (perhaps other browsers but I've read the code in Chrome) a certificate in which the lifespan (between NotBefore and NotAfter) exceeds the maximum permissible lifespan at that issuance date, it treats the certificate as invalid anyway.
By the way, there have been a number of openly government-operated root CAs in numerous countries for decades. Before I got involved with Let's Encrypt, I was very nervous about government influence in PKI and thought this was quite concerning. (That was also before Certificate Transparency.)
A quick look at a root store turns up
subject=C = CN, O = China Financial Certification Authority, CN = CFCA EV ROOT
subject=C = HK, O = Hongkong Post, CN = Hongkong Post Root CA 1
subject=C = NL, O = Staat der Nederlanden, CN = Staat der Nederlanden EV Root CA [and other roots with the same organization]
subject=C = TW, O = Government Root Certification Authority
I think there are several others, probably especially at the intermediate level.
Just what we need is to get politicians involved in this.
One benefit thought would be they could more easily block access to sites they don't want folks visiting by just denying a CA cert (which would then generate warnings / blocking in many browsers).
I would like to hear from the planetary president to see what he has to say about that.
Seriously this is all great but unfortunately with all the mess going on with "the big powers" I'm not sure you want to give them that. I wished we lived in a world where we could tho.
Cloud flare is American and we know since the PRISM scandal that US based tech companies are directly plugged into the NSA, and everybody in the chain will deny it under the threat of prison.
So, if this rolls out 'as-is' in any other country than the US, we will go from "all DNS requests are clear text, but dispatched among many entities" to "DNS requests are encrypted, but all read and controlled by american agencies".
We (may) have gain (some) privacy (maybe). But we also (certainly) gained a serious dependency.
NSA don’t factor into my personal threat model _at all_ where random ISPs snooping and selling do. I would gladly give the NSA all of my traffic unencrypted in exchange for decent commercial privacy
I supposed not having a dictatorship regime in your country history book helps to see things that way.
Given the way my country went from freedom to "regime de Vichy" in a few years, during my grandpa time, I don't want a state level entity having that kind of power.
Since the US state level entities decided they could now ignore Habeas Corpus and legitimated torture, secret courts and declared impunity for them-self, I especially don't want them to have that kind of power.
If a malicious power takes over your country they’ll hit you with a rubber hose until you give up your secrets much before they give a shit about your internet history, I suspect.
Quite the contrary, as shown by as most dictatorships across the world trying to control their piece of the internet. The biggest example being the Big Firewall of China.
This let them control how people think, communicate, consume and inform them-self. But also detects anyone that could oppose the regime. Or make a graph of all allies, suspects, etc.
I don't think it is. If JS had any sane competition, I think it would have lost. By some weird conjunction of events, it landed a monopoly on the most amazing plateform in the world.
PHP is a good example of Worse is Better, because it won over the competition, despite its flaws.
Don't get me wrong, I find it funny. The current trend of humble brag is a good topic to laugh about.
But do you want an entire article about this? Do you want that to be on HN front page?
There are thousands of such joke accounts. Are we going to post about them all?