{"id":1658,"date":"2014-12-03T14:15:26","date_gmt":"2014-12-03T03:15:26","guid":{"rendered":"http:\/\/www.malcolmgroves.com\/blog\/?p=1658"},"modified":"2014-12-05T14:57:37","modified_gmt":"2014-12-05T03:57:37","slug":"what-happens-after-tparallel-waitforany-returns","status":"publish","type":"post","link":"http:\/\/www.malcolmgroves.com\/blog\/?p=1658","title":{"rendered":"What happens after TParallel.WaitForAny returns?"},"content":{"rendered":"<p>I was showing off the new Parallel Programming Library (PPL) at a recent event, in particular the demo where we spawn off a couple of tasks and then wait for only one of them to finish. The code in question looked like this:<!--more--><\/p>\n<pre>procedure TFormThreading.Button2Click(Sender: TObject);\r\nvar\r\n  tasks: array of ITask;\r\n  value: Integer;\r\nbegin\r\n  Setlength (tasks ,2);\r\n  value := 0;\r\n\r\n  tasks[0] := TTask.Create (procedure\r\n                            begin\r\n                              sleep (3000);\r\n                              TInterlocked.Add(value, 3000);\r\n                            end);\r\n  tasks[0].Start;\r\n  tasks[1] := TTask.Create (procedure\r\n                            begin\r\n                              sleep (5000);\r\n                              TInterlocked.Add (value, 5000);\r\n                            end);\r\n  tasks[1].Start;\r\n  TTask.WaitForAny(tasks);\r\n  \r\n  ShowMessage ('First task done: ' + value.ToString);\r\nend;<\/pre>\n<p>As you can see, we&#8217;re creating two tasks:<\/p>\n<ul>\n<li>the first will sleep for 3000 milliseconds (3 seconds) and then add 3000 to a local variable called value<\/li>\n<li>the second will sleep for 5000 milliseconds and then add 5000 to value<\/li>\n<\/ul>\n<p>We start them both and then wait for the first one to finish (on the line where we call TTask.WaitForAny(tasks))<\/p>\n<p>So what will the variable &#8220;value&#8221; hold immediately after WaitForAny returns? That should be easy. Even allowing for scheduling differences, it should be 3000.<\/p>\n<p>But what you may not realise is the second task is still running. If you don&#8217;t believe me, put a breakpoint on the call to Tinterlocked.Add in the second task, debug the method and then leave the ShowMessage dialog up for longer than 2 seconds (giving the second task time to finish) and your breakpoint should fire.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-1675 size-full\" title=\"parallel man - http:\/\/www.comicvine.com\/parallel-man-invasion-america-2\/4000-468612\/\" src=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2014\/11\/parallelman1.jpg\" alt=\"parallel man - http:\/\/www.comicvine.com\/parallel-man-invasion-america-2\/4000-468612\/\" width=\"400\" height=\"615\" srcset=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2014\/11\/parallelman1.jpg 400w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2014\/11\/parallelman1-195x300.jpg 195w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>This is important to understand. Depending on your app, and what you are doing in your tasks, this might matter a lot. \u00a0Let&#8217;s say we were doing something else with &#8220;value&#8221; after the call to ShowMessage. It&#8217;s possible that between the call to ShowMessage (where value was equal to 3000) and the next line where we were using it, it&#8217;s value could become 8000.<\/p>\n<p>So, what should we do if we don&#8217;t want this to happen?<\/p>\n<p>Firstly, after WaitForAny returns, we should cancel the other tasks. Some code like the following will loop through all the tasks, cancelling any that have not completed.<\/p>\n<pre>  TTask.WaitForAny(tasks);\r\n  for LTask in tasks do\r\n    LTask.Cancel;\r\n  ShowMessage ('All done: ' + value.ToString);<\/pre>\n<p>where LTask is just a local variable\u00a0of type ITask.<\/p>\n<p>That&#8217;s a good start, but calling Cancel on a Task doesn&#8217;t actually cancel the task. That might sound a little odd at first, but all you are really doing is signalling to the task that it should cancel itself. It&#8217;s up to the logic inside the anonymous method you pass the task to check for this status.<\/p>\n<p>When should you check it? Depends on what you&#8217;re doing, but there are a few likely places:<\/p>\n<ul>\n<li>Right at the start of your Task. Remember, you might have tasks that have not yet started, due to waiting for threads to become available in the Thread Pool, so if they have been cancelled before they have even started, may as well find that out early and get out before doing any work.<\/li>\n<li>If the task is long running, you might check it at regular intervals, so you can bail out and stop any time- or resource-consuming activity as early as possible. Let&#8217;s say you are in a loop, you might check it every time around the loop, or every x times around the loop, depending on the work you are doing.<\/li>\n<li>While the above two might be optional in your app, I&#8217;d say this one is mandatory. In my opinion you should absolutely check it before you make any changes outside your task, like updating the UI or in this case, writing back to the &#8220;value&#8221; variable, like so:<\/li>\n<\/ul>\n<pre class=\"\">  sleep (5000); \/\/ 5 seconds\r\n  if tasks[1].Status &lt;&gt; TTaskStatus.Canceled then\r\n    TInterlocked.Add (value, 5000);<\/pre>\n<p>So here&#8217;s what my revised code looks like in total:<\/p>\n<pre class=\"\">procedure TFormThreading.Button2Click(Sender: TObject);\r\nvar\r\n  tasks: array of ITask;\r\n  value: Integer;\r\n  LTask: ITask;\r\nbegin\r\n  Setlength (tasks ,2);\r\n  value := 0;\r\n\r\n  tasks[0] := TTask.Create(procedure\r\n                           begin\r\n                             sleep (3000);\r\n                             if tasks[0].Status &lt;&gt; TTaskStatus.Canceled then\r\n                               TInterlocked.Add(value, 3000);\r\n                           end);\r\n  tasks[0].Start;\r\n\r\n  tasks[1] := TTask.Create(procedure\r\n                           begin\r\n                             sleep (5000);\r\n                             if tasks[1].Status &lt;&gt; TTaskStatus.Canceled then\r\n                               TInterlocked.Add (value, 5000);\r\n                           end);\r\n  tasks[1].Start;\r\n\r\n  TTask.WaitForAny(tasks);\r\n  for LTask in tasks do\r\n    LTask.Cancel;\r\n  ShowMessage('All done: ' + value.ToString);\r\nend;<\/pre>\n<p>&nbsp;<\/p>\n<p>My main point with this post was to highlight that Tasks continue on, even if you&#8217;re not waiting for them anymore, so checking for the Cancelled flag and ending your tasks as soon as possible is a good thing. However, we&#8217;re not quite done here. <strong>There is still a potential race condition in this code<\/strong>, <a title=\"\u201cBut what happens if\u2026\u201d : The Joy of Race Conditions\" href=\"http:\/\/www.malcolmgroves.com\/blog\/?p=1730\">which I&#8217;ll resolve in the next post<\/a>.<\/p>\n<p>If you&#8217;re looking for more details on the PPL, including some meatier examples, check out <a href=\"http:\/\/dannywind.nl\/\" target=\"_blank\">Danny Wind<\/a>&#8216;s CodeRage 9 session, and stay all the way to the end.<\/p>\n<p><iframe loading=\"lazy\" width=\"560\" height=\"315\" src=\"\/\/www.youtube.com\/embed\/rZfux4by0po?list=PLwUPJvR9mZHhgQYWWgF6BCkgDwIpP78ZV\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\"><\/iframe><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I was showing off the new Parallel Programming Library (PPL) at a recent event, in particular the demo where we spawn off a couple of tasks and then wait for only one of them to finish. The code in question looked like this:<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[98,123],"tags":[48,109],"class_list":["post-1658","post","type-post","status-publish","format-standard","hentry","category-coding","category-parallel","tag-embarcadero","tag-parallel"],"_links":{"self":[{"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1658","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1658"}],"version-history":[{"count":29,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1658\/revisions"}],"predecessor-version":[{"id":1736,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1658\/revisions\/1736"}],"wp:attachment":[{"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1658"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1658"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1658"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}