{"id":2720,"date":"2018-06-20T05:45:31","date_gmt":"2018-06-20T05:45:31","guid":{"rendered":"http:\/\/98.80.187.15\/?p=2720"},"modified":"2024-07-23T22:29:48","modified_gmt":"2024-07-24T02:29:48","slug":"load-balancing-python","status":"publish","type":"post","link":"https:\/\/esologic.com\/load-balancing-python\/","title":{"rendered":"Why you should use Processes instead of Threads to isolate loads in Python"},"content":{"rendered":"<h2>Key Learning<\/h2>\n<p>Python uses a <a href=\"https:\/\/wiki.python.org\/moin\/GlobalInterpreterLock\">Global Interpreter Lock<\/a> to make sure that\u00a0 memory shared between threads isn&#8217;t corrupted. This is a design choice of the language that has it&#8217;s pros and cons. One of these cons is that in multi-threaded applications where at least one\u00a0 thread applies a large load to the CPU, all other threads will slow down as well.<\/p>\n<p><strong>For multi-threaded Python applications that are at least somewhat time-sensitive, you should use <a href=\"https:\/\/docs.python.org\/3.6\/library\/multiprocessing.html#multiprocessing.Process\">Processes<\/a> over <a href=\"https:\/\/docs.python.org\/3.6\/library\/threading.html#threading.Thread\">Threads<\/a>.<\/strong><\/p>\n<h2>Experiment<\/h2>\n<p>I wrote a simple python script to show this phenomenon. Let&#8217;s take a look.<\/p>\n<pre class=\"lang:python decode:true \" title=\"Increment Function\">def increment(running_flag, count_value):\r\n    c = 0\r\n    while True:\r\n        if not running_flag.value:\r\n            break\r\n        count_value.value = c  # setting a Value is atomic\r\n        c += 1<\/pre>\n<p>The core is this increment function. It takes in a <a href=\"https:\/\/docs.python.org\/3.6\/library\/multiprocessing.html#multiprocessing.Value\">Value<\/a> and then sets it over and over, increment each loop, until the <code>running_flag<\/code>\u00a0is set to false. The value of <code>count_value<\/code>\u00a0is what is graphed later on, and is the measure of how fast things are going.<\/p>\n<p>The other important bit is the load function:<\/p>\n<pre class=\"lang:python decode:true\" title=\"Load Function\">def load(running_flag):\r\n    z = 10\r\n    while True:\r\n        if not running_flag.value:\r\n            break\r\n        z = z * z<\/pre>\n<p>Like <code>increment<\/code>,\u00a0 <code>load<\/code>\u00a0is the target of a thread or process. The <code>z<\/code>\u00a0variable quickly becomes large and computing the loop becomes difficult quickly.<\/p>\n<p>The rest of the code is just a way to have different combinations of <code>increment<\/code>\u00a0and <code>load<\/code>\u00a0running at the same time for varying amounts of time.<\/p>\n<h2>Result<\/h2>\n<p><a href=\"https:\/\/www.esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2721\" src=\"https:\/\/www.esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png\" alt=\"\" width=\"690\" height=\"743\" srcset=\"https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png 690w, https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph-600x646.png 600w, https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph-279x300.png 279w, https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph-644x693.png 644w\" sizes=\"auto, (max-width: 690px) 100vw, 690px\" \/><\/a><\/p>\n<p>The graph really tells the story. Without the load thread running, the process and thread versions of <code>increment<\/code>\u00a0run at essentially the same rate. When the load thread is running, <code>increment<\/code>\u00a0 in a thread grinds to a halt compared to the process which is unaffected.<\/p>\n<p>That&#8217;s all! I&#8217;ve pasted the full source below so you can try the experiment yourself.<\/p>\n<pre class=\"lang:python decode:true\" title=\"Full Source\">from multiprocessing import Process, Value\r\nfrom threading import Thread\r\nfrom time import sleep\r\nfrom ctypes import c_bool, c_longdouble\r\n\r\n\r\ndef increment(running_flag, count_value):\r\n    \"\"\"\r\n    Increment the value in count_value as quickly as possible. If running_flag is set to false, break out of the loop\r\n    :param running_flag: a multiprocessing.Value boolean\r\n    :param count_value: a multiprocessing.Value Long Double\r\n    \"\"\"\r\n\r\n    c = 0\r\n\r\n    while True:\r\n\r\n        if not running_flag.value:\r\n            break\r\n\r\n        count_value.value = c  # setting a Value is atomic\r\n        c += 1\r\n\r\n\r\ndef load(running_flag):\r\n    \"\"\"\r\n    Apply a load to the CPU. If running_flag is set to false, break out of the loop\r\n    :param running_flag: a multiprocessing.Value boolean\r\n    \"\"\"\r\n\r\n    z = 10\r\n\r\n    while True:\r\n\r\n        if not running_flag.value:\r\n            break\r\n\r\n        z = z * z\r\n\r\n\r\ndef mct(target, flag, value):\r\n    \"\"\"\r\n    Returns a lambda that can be called to get a thread to increment a increment using a thread\r\n    \"\"\"\r\n    return lambda: Thread(target=target, args=(flag, value))\r\n\r\n\r\ndef mcp(target, flag, value):\r\n    \"\"\"\r\n    Returns a lambda that can be called to get a thread to increment a increment using a process\r\n    \"\"\"\r\n    return lambda: Process(target=target, args=(flag, value))\r\n\r\n\r\ndef mlt(target, flag):\r\n    \"\"\"\r\n    Returns a lambda that can be called to get a thread that will load down the CPU\r\n    \"\"\"\r\n    return lambda: Thread(target=target, args=(flag,))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n    f = Value(c_bool, True)  # control flag, will be passed into child thread\/process so they can be stopped\r\n    cv = Value(c_longdouble, 0)  # increment value\r\n\r\n    child_lists = [mct(increment, f, cv)], [mcp(increment, f, cv)], [mct(increment, f, cv), mlt(load, f)], [mcp(increment, f, cv), mlt(load, f)]\r\n\r\n    for delay in range(10):  # maximum run time of 10 seconds\r\n\r\n        max_counts = []\r\n\r\n        for get_children in child_lists:\r\n\r\n            # reset the flag and increment\r\n            f.value = True\r\n            cv.value = 0\r\n\r\n            # the child thread\/processes will end up in here\r\n            children = []\r\n\r\n            for get_child in get_children:\r\n                child = get_child()  # create a new instance of the thread\/process to be launched\r\n                child.start()\r\n                children.append(child)\r\n\r\n            sleep(delay)\r\n\r\n            f.value = False\r\n\r\n            for child in children:\r\n                child.join()  # stop the process\r\n\r\n            max_counts.append(cv.value)\r\n\r\n        s = \"\"\r\n        for count in max_counts:\r\n            s += str(count) + \" \"\r\n        print(s)<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Key Learning Python uses a Global Interpreter Lock to make sure that\u00a0 memory shared between threads isn&#8217;t corrupted. This is a design choice of the language that has it&#8217;s pros and cons. One of these cons is that in multi-threaded applications where at least one\u00a0 thread applies a large load to the CPU, all other&#8230;<\/p>\n","protected":false},"author":1,"featured_media":2721,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[162],"tags":[177],"class_list":["post-2720","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-demo","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Why you should use Processes instead of Threads to isolate loads in Python - esologic<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/esologic.com\/load-balancing-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Why you should use Processes instead of Threads to isolate loads in Python - esologic\" \/>\n<meta property=\"og:description\" content=\"Key Learning Python uses a Global Interpreter Lock to make sure that\u00a0 memory shared between threads isn&#8217;t corrupted. This is a design choice of the language that has it&#8217;s pros and cons. One of these cons is that in multi-threaded applications where at least one\u00a0 thread applies a large load to the CPU, all other...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/esologic.com\/load-balancing-python\/\" \/>\n<meta property=\"og:site_name\" content=\"esologic\" \/>\n<meta property=\"article:published_time\" content=\"2018-06-20T05:45:31+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-07-24T02:29:48+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png\" \/>\n\t<meta property=\"og:image:width\" content=\"690\" \/>\n\t<meta property=\"og:image:height\" content=\"743\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Devon\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Devon\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/\"},\"author\":{\"name\":\"Devon\",\"@id\":\"https:\\\/\\\/esologic.com\\\/#\\\/schema\\\/person\\\/25fe9b9fbfd4f40d9de0eb261a8ae84d\"},\"headline\":\"Why you should use Processes instead of Threads to isolate loads in Python\",\"datePublished\":\"2018-06-20T05:45:31+00:00\",\"dateModified\":\"2024-07-24T02:29:48+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/\"},\"wordCount\":269,\"commentCount\":0,\"image\":{\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/esologic.com\\\/wp-content\\\/uploads\\\/2018\\\/06\\\/load_balance_graph.png\",\"keywords\":[\"python\"],\"articleSection\":[\"Demo\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/\",\"url\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/\",\"name\":\"Why you should use Processes instead of Threads to isolate loads in Python - esologic\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/esologic.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/esologic.com\\\/wp-content\\\/uploads\\\/2018\\\/06\\\/load_balance_graph.png\",\"datePublished\":\"2018-06-20T05:45:31+00:00\",\"dateModified\":\"2024-07-24T02:29:48+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/esologic.com\\\/#\\\/schema\\\/person\\\/25fe9b9fbfd4f40d9de0eb261a8ae84d\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/#primaryimage\",\"url\":\"https:\\\/\\\/esologic.com\\\/wp-content\\\/uploads\\\/2018\\\/06\\\/load_balance_graph.png\",\"contentUrl\":\"https:\\\/\\\/esologic.com\\\/wp-content\\\/uploads\\\/2018\\\/06\\\/load_balance_graph.png\",\"width\":690,\"height\":743},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/esologic.com\\\/load-balancing-python\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/esologic.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Why you should use Processes instead of Threads to isolate loads in Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/esologic.com\\\/#website\",\"url\":\"https:\\\/\\\/esologic.com\\\/\",\"name\":\"esologic\",\"description\":\"Devon Bray&#039;s Project Portfolio &amp; Development Blog\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/esologic.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/esologic.com\\\/#\\\/schema\\\/person\\\/25fe9b9fbfd4f40d9de0eb261a8ae84d\",\"name\":\"Devon\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3c0b44a1be0009def7725519abcf6e05c45f3d6b91e1b088de12d97ccd4ae3b6?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3c0b44a1be0009def7725519abcf6e05c45f3d6b91e1b088de12d97ccd4ae3b6?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3c0b44a1be0009def7725519abcf6e05c45f3d6b91e1b088de12d97ccd4ae3b6?s=96&d=mm&r=g\",\"caption\":\"Devon\"},\"sameAs\":[\"https:\\\/\\\/esologic.com\"],\"url\":\"https:\\\/\\\/esologic.com\\\/author\\\/devon\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Why you should use Processes instead of Threads to isolate loads in Python - esologic","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/esologic.com\/load-balancing-python\/","og_locale":"en_US","og_type":"article","og_title":"Why you should use Processes instead of Threads to isolate loads in Python - esologic","og_description":"Key Learning Python uses a Global Interpreter Lock to make sure that\u00a0 memory shared between threads isn&#8217;t corrupted. This is a design choice of the language that has it&#8217;s pros and cons. One of these cons is that in multi-threaded applications where at least one\u00a0 thread applies a large load to the CPU, all other...","og_url":"https:\/\/esologic.com\/load-balancing-python\/","og_site_name":"esologic","article_published_time":"2018-06-20T05:45:31+00:00","article_modified_time":"2024-07-24T02:29:48+00:00","og_image":[{"width":690,"height":743,"url":"https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png","type":"image\/png"}],"author":"Devon","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Devon","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/esologic.com\/load-balancing-python\/#article","isPartOf":{"@id":"https:\/\/esologic.com\/load-balancing-python\/"},"author":{"name":"Devon","@id":"https:\/\/esologic.com\/#\/schema\/person\/25fe9b9fbfd4f40d9de0eb261a8ae84d"},"headline":"Why you should use Processes instead of Threads to isolate loads in Python","datePublished":"2018-06-20T05:45:31+00:00","dateModified":"2024-07-24T02:29:48+00:00","mainEntityOfPage":{"@id":"https:\/\/esologic.com\/load-balancing-python\/"},"wordCount":269,"commentCount":0,"image":{"@id":"https:\/\/esologic.com\/load-balancing-python\/#primaryimage"},"thumbnailUrl":"https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png","keywords":["python"],"articleSection":["Demo"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/esologic.com\/load-balancing-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/esologic.com\/load-balancing-python\/","url":"https:\/\/esologic.com\/load-balancing-python\/","name":"Why you should use Processes instead of Threads to isolate loads in Python - esologic","isPartOf":{"@id":"https:\/\/esologic.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/esologic.com\/load-balancing-python\/#primaryimage"},"image":{"@id":"https:\/\/esologic.com\/load-balancing-python\/#primaryimage"},"thumbnailUrl":"https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png","datePublished":"2018-06-20T05:45:31+00:00","dateModified":"2024-07-24T02:29:48+00:00","author":{"@id":"https:\/\/esologic.com\/#\/schema\/person\/25fe9b9fbfd4f40d9de0eb261a8ae84d"},"breadcrumb":{"@id":"https:\/\/esologic.com\/load-balancing-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/esologic.com\/load-balancing-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/esologic.com\/load-balancing-python\/#primaryimage","url":"https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png","contentUrl":"https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png","width":690,"height":743},{"@type":"BreadcrumbList","@id":"https:\/\/esologic.com\/load-balancing-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/esologic.com\/"},{"@type":"ListItem","position":2,"name":"Why you should use Processes instead of Threads to isolate loads in Python"}]},{"@type":"WebSite","@id":"https:\/\/esologic.com\/#website","url":"https:\/\/esologic.com\/","name":"esologic","description":"Devon Bray&#039;s Project Portfolio &amp; Development Blog","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/esologic.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/esologic.com\/#\/schema\/person\/25fe9b9fbfd4f40d9de0eb261a8ae84d","name":"Devon","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/3c0b44a1be0009def7725519abcf6e05c45f3d6b91e1b088de12d97ccd4ae3b6?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/3c0b44a1be0009def7725519abcf6e05c45f3d6b91e1b088de12d97ccd4ae3b6?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/3c0b44a1be0009def7725519abcf6e05c45f3d6b91e1b088de12d97ccd4ae3b6?s=96&d=mm&r=g","caption":"Devon"},"sameAs":["https:\/\/esologic.com"],"url":"https:\/\/esologic.com\/author\/devon\/"}]}},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/esologic.com\/wp-content\/uploads\/2018\/06\/load_balance_graph.png","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/posts\/2720","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/comments?post=2720"}],"version-history":[{"count":9,"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/posts\/2720\/revisions"}],"predecessor-version":[{"id":2865,"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/posts\/2720\/revisions\/2865"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/media\/2721"}],"wp:attachment":[{"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/media?parent=2720"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/categories?post=2720"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/esologic.com\/wp-json\/wp\/v2\/tags?post=2720"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}