<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>threading Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/threading/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/threading/</link>
	<description></description>
	<lastBuildDate>Wed, 24 Jul 2019 10:45:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>threading Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/threading/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1116. Print Zero Even Odd</title>
		<link>https://zxi.mytechroad.com/blog/concurrent/leetcode-1116-print-zero-even-odd/</link>
					<comments>https://zxi.mytechroad.com/blog/concurrent/leetcode-1116-print-zero-even-odd/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 24 Jul 2019 10:45:27 +0000</pubDate>
				<category><![CDATA[Concurrent]]></category>
		<category><![CDATA[concurrent]]></category>
		<category><![CDATA[lock]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[mutex]]></category>
		<category><![CDATA[threading]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5351</guid>

					<description><![CDATA[<p>Suppose you are given the following code: class ZeroEvenOdd { &#160; public ZeroEvenOdd(int n) { ... }&#160; // constructor public void zero(printNumber) { ... }&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1116-print-zero-even-odd/">花花酱 LeetCode 1116. Print Zero Even Odd</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Suppose you are given the following code:</p>



<pre class="wp-block-preformatted; crayon:false">class ZeroEvenOdd {
&nbsp; public ZeroEvenOdd(int n) { ... }&nbsp;     // constructor
  public void zero(printNumber) { ... }  // only output 0's
  public void even(printNumber) { ... }  // only output even numbers
  public void odd(printNumber) { ... }   // only output odd numbers
}
</pre>



<p>The same instance of&nbsp;<code>ZeroEvenOdd</code>&nbsp;will be passed to three different threads:</p>



<ol><li>Thread A will call&nbsp;<code>zero()</code>&nbsp;which should only output 0&#8217;s.</li><li>Thread B will call&nbsp;<code>even()</code>&nbsp;which should only ouput even numbers.</li><li>Thread C will call&nbsp;<code>odd()</code>&nbsp;which should only output odd numbers.</li></ol>



<p>Each of the thread is given a&nbsp;<code>printNumber</code>&nbsp;method to output&nbsp;an integer. Modify the given program to output the series&nbsp;<code>010203040506</code>&#8230; where the length of the series must be 2<em>n</em>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted; crayon:false"><strong>Input:</strong> n = 2
<strong>Output:</strong> "0102"
<strong>Explanation:</strong> There are three threads being fired asynchronously. One of them calls zero(), the other calls even(), and the last one calls odd(). "0102" is the correct output.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted; crayon:false"><strong>Input:</strong> n = 5
<strong>Output:</strong> "0102030405"</pre>



<h2><strong>Solution: Mutex</strong></h2>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 40 ms / 9 MB
class ZeroEvenOdd {
private:
  int x;
  int n;
  mutex m_zero_;
  mutex m_odd_;
  mutex m_even_;
public:
    ZeroEvenOdd(int n) {
      this-&gt;n = n;
      this-&gt;x = 1;
      m_odd_.lock();
      m_even_.lock();
    }

    // printNumber(x) outputs &quot;x&quot;, where x is an integer.
    void zero(function&lt;void(int)&gt; printNumber) {
      for (int i = 0; i &lt; n; ++i) {
        m_zero_.lock();
        printNumber(0);
        if (i % 2 == 0) {
          m_odd_.unlock();
        } else {
          m_even_.unlock();
        }
      }
    }

    void even(function&lt;void(int)&gt; printNumber) {
      for (int i = 2; i &lt;= n; i += 2) {
        m_even_.lock();
        printNumber(i);
        m_zero_.unlock();
      }
    }

    void odd(function&lt;void(int)&gt; printNumber) {
      for (int i = 1; i &lt;= n; i += 2) {
        m_odd_.lock();
        printNumber(i);
        m_zero_.unlock();      
      }
    }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1116-print-zero-even-odd/">花花酱 LeetCode 1116. Print Zero Even Odd</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/concurrent/leetcode-1116-print-zero-even-odd/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1115. Print FooBar Alternately</title>
		<link>https://zxi.mytechroad.com/blog/concurrent/leetcode-1115-print-foobar-alternately/</link>
					<comments>https://zxi.mytechroad.com/blog/concurrent/leetcode-1115-print-foobar-alternately/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 23 Jul 2019 16:22:32 +0000</pubDate>
				<category><![CDATA[Concurrent]]></category>
		<category><![CDATA[concurrent]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[mutex]]></category>
		<category><![CDATA[threading]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5347</guid>

					<description><![CDATA[<p>Suppose you are given the following code: class FooBar { public void foo() { &#160; &#160; for (int i = 0; i &#60; n; i++)&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1115-print-foobar-alternately/">花花酱 LeetCode 1115. Print FooBar Alternately</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Suppose you are given the following code:</p>



<pre class="wp-block-preformatted; crayon:false">class FooBar {
  public void foo() {
&nbsp; &nbsp; for (int i = 0; i &lt; n; i++) {
&nbsp; &nbsp; &nbsp; print("foo");
&nbsp;   }
  }

  public void bar() {
&nbsp; &nbsp; for (int i = 0; i &lt; n; i++) {
&nbsp; &nbsp; &nbsp; print("bar");
&nbsp; &nbsp; }
  }
}
</pre>



<p>The same instance of&nbsp;<code>FooBar</code>&nbsp;will be passed to two different threads. Thread A will call&nbsp;<code>foo()</code>&nbsp;while thread B will call&nbsp;<code>bar()</code>.&nbsp;Modify the given program to output &#8220;foobar&#8221;&nbsp;<em>n</em>&nbsp;times.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 1
<strong>Output:</strong> "foobar"
<strong>Explanation:</strong> There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2
<strong>Output:</strong> "foobarfoobar"
<strong>Explanation:</strong> "foobar" is being output 2 times.</pre>



<h2><strong>Solution: Mutex</strong></h2>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class FooBar {
private:
  int n;
  std::mutex m1_;
  std::mutex m2_; 
public:
  FooBar(int n) {
    this-&gt;n = n;    
    m2_.lock();
  }

  void foo(function&lt;void()&gt; printFoo) {

      for (int i = 0; i &lt; n; i++) {
        m1_.lock();
        // printFoo() outputs &quot;foo&quot;. Do not change or remove this line.
        printFoo();
        m2_.unlock();
      }
  }

  void bar(function&lt;void()&gt; printBar) {

      for (int i = 0; i &lt; n; i++) {
        m2_.lock();
        // printBar() outputs &quot;bar&quot;. Do not change or remove this line.
        printBar();
        m1_.unlock();
      }
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1115-print-foobar-alternately/">花花酱 LeetCode 1115. Print FooBar Alternately</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/concurrent/leetcode-1115-print-foobar-alternately/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1114. Print in Order</title>
		<link>https://zxi.mytechroad.com/blog/concurrent/leetcode-1114-print-in-order/</link>
					<comments>https://zxi.mytechroad.com/blog/concurrent/leetcode-1114-print-in-order/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 23 Jul 2019 15:58:56 +0000</pubDate>
				<category><![CDATA[Concurrent]]></category>
		<category><![CDATA[concurrent]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[mutex]]></category>
		<category><![CDATA[threading]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5344</guid>

					<description><![CDATA[<p>Suppose we have a class: [crayon-663a17fc3fc6b406363935/] The same instance of&#160;Foo&#160;will be passed to three different threads. Thread A will call&#160;first(), thread B will call&#160;second(), and&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1114-print-in-order/">花花酱 LeetCode 1114. Print in Order</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Suppose we have a class:</p>



<pre class="crayon-plain-tag">public class Foo {
&amp;nbsp; public void first() { print(&quot;first&quot;); }
&amp;nbsp; public void second() { print(&quot;second&quot;); }
&amp;nbsp; public void third() { print(&quot;third&quot;); }
}</pre>



<p>The same instance of&nbsp;<code>Foo</code>&nbsp;will be passed to three different threads. Thread A will call&nbsp;<code>first()</code>, thread B will call&nbsp;<code>second()</code>, and thread C will call&nbsp;<code>third()</code>. Design a mechanism and modify the program&nbsp;to ensure that&nbsp;<code>second()</code>&nbsp;is executed after&nbsp;<code>first()</code>, and&nbsp;<code>third()</code>&nbsp;is executed after&nbsp;<code>second()</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> [1,2,3]
<strong>Output:</strong> "firstsecondthird"
<strong>Explanation:</strong> There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> [1,3,2]
<strong>Output:</strong> "firstsecondthird"
<strong>Explanation:</strong> The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.</pre>



<p><strong>Note:</strong></p>



<p>We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seems to imply the ordering. The input format you see is mainly to ensure our tests&#8217; comprehensiveness.</p>



<h2><strong>Solution 1: Mutex</strong></h2>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 128 ms / 8.2 MB
class Foo {
public:
    Foo() {
      first_.lock();
      second_.lock();
    }

    void first(function&lt;void()&gt; printFirst) {        
      // printFirst() outputs &quot;first&quot;. Do not change or remove this line.
      printFirst();  
      first_.unlock();
    }

    void second(function&lt;void()&gt; printSecond) {            
      first_.lock();
      // printSecond() outputs &quot;second&quot;. Do not change or remove this line.
      printSecond();
      first_.unlock();
      second_.unlock();
    }

    void third(function&lt;void()&gt; printThird) {
      second_.lock();
      // printThird() outputs &quot;third&quot;. Do not change or remove this line.
      printThird();      
      second_.unlock();
    }
private:
  std::mutex first_;
  std::mutex second_;
};</pre>
</div></div>



<h2><strong>Solution 2: Busy waiting</strong></h2>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 176 ms / 9.2 MB
#include &lt;unistd.h&gt;

class Foo {
public:
    Foo() {}

    void first(function&lt;void()&gt; printFirst) {        
      // printFirst() outputs &quot;first&quot;. Do not change or remove this line.
      printFirst();  
      state_ = 1;
    }

    void second(function&lt;void()&gt; printSecond) {            
      while (state_ != 1) usleep(1);
      // printSecond() outputs &quot;second&quot;. Do not change or remove this line.
      printSecond();
      state_ = 2;
    }

    void third(function&lt;void()&gt; printThird) {
      while (state_ != 2) usleep(1);
      // printThird() outputs &quot;third&quot;. Do not change or remove this line.
      printThird();      
      state_ = 3;
    }
private:
  int state_ = 0;
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1114-print-in-order/">花花酱 LeetCode 1114. Print in Order</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/concurrent/leetcode-1114-print-in-order/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
