简体   繁体   中英

Google CloudFunctions: ContextVar vs Global Var

Is there a difference between ContextVar and Global Var within Google Cloud Functions?

I noticed that as Google tries to re-use GCF instances some global vars classes are reused from one GCF invocation to another and not init at the start of each GCF invocation. I need each of those global var classes to be unique for each GCF invocation.

Are ContextVars unique for each GCF invocation?

Currently I assign those global vars to None and re-init afterwards to ensure fresh init of each class

You have your Cloud Functions, I assume, an HTTP cloud functions. (same with background functions, it's just for my example).

Now, test your HTTP Cloud Functions: create a webserver (with flask for example because you seem in Python).

Start your webserver.


That's for the context. Now my explanation:

  • When a Cloud Functions is created, the platform run a webserver (flask) as you create it.
  • When a request comes in, the webserver get it and call the "function" to process it (ie the Cloud Functions).

So, the GlobalVars and the ContextVars on Cloud Functions have exactly the same lifecycle than them in your local webserver. There is no magic/strange stuff.

More useful, you can test this locally, it's quicker and easier!

For the future generations

GCFs are single thread so ContextVars don't have any impact - there is always just 1 thread. Nevertheless GCF instances could be re-used, so GlobarVars may continue to exist and should be re-initialized after GCF call if the GlobalVars are instance specific

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM