<?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>concurrent Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/concurrent/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/concurrent/</link>
	<description></description>
	<lastBuildDate>Sun, 22 Sep 2019 10:53:48 +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>concurrent Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/concurrent/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1195. Fizz Buzz Multithreaded</title>
		<link>https://zxi.mytechroad.com/blog/concurrent/leetcode-1195-fizz-buzz-multithreaded/</link>
					<comments>https://zxi.mytechroad.com/blog/concurrent/leetcode-1195-fizz-buzz-multithreaded/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Sep 2019 10:53:38 +0000</pubDate>
				<category><![CDATA[Concurrent]]></category>
		<category><![CDATA[concurrent]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[multithreading]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5579</guid>

					<description><![CDATA[<p>Write a program that outputs the string representation of numbers from 1 to&#160;n, however: If the number is divisible by 3, output &#8220;fizz&#8221;. If the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1195-fizz-buzz-multithreaded/">花花酱 LeetCode 1195. Fizz Buzz Multithreaded</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>Write a program that outputs the string representation of numbers from 1 to&nbsp;<em>n</em>, however:</p>



<ul><li>If the number is divisible by 3, output &#8220;fizz&#8221;.</li><li>If the number is divisible by 5, output&nbsp;&#8220;buzz&#8221;.</li><li>If the number is divisible by both 3 and 5, output&nbsp;&#8220;fizzbuzz&#8221;.</li></ul>



<p>For example, for&nbsp;<code>n = 15</code>, we output:&nbsp;<code>1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz</code>.</p>



<p>Suppose you are given the following code:</p>



<pre class="wp-block-preformatted;crayon:false">class FizzBuzz {
&nbsp; public FizzBuzz(int n) { ... }&nbsp;              // constructor
  public void fizz(printFizz) { ... }          // only output "fizz"
  public void buzz(printBuzz) { ... }          // only output "buzz"
  public void fizzbuzz(printFizzBuzz) { ... }  // only output "fizzbuzz"
  public void number(printNumber) { ... }      // only output the numbers
}</pre>



<p>Implement a multithreaded version of&nbsp;<code>FizzBuzz</code>&nbsp;with&nbsp;<strong>four</strong>&nbsp;threads. The same instance of&nbsp;<code>FizzBuzz</code>&nbsp;will be passed to four different threads:</p>



<ol><li>Thread A will call&nbsp;<code>fizz()</code>&nbsp;to check for divisibility of 3 and outputs&nbsp;<code>fizz</code>.</li><li>Thread B will call&nbsp;<code>buzz()</code>&nbsp;to check for divisibility of 5 and outputs&nbsp;<code>buzz</code>.</li><li>Thread C will call&nbsp;<code>fizzbuzz()</code>&nbsp;to check for divisibility of 3 and 5 and outputs&nbsp;<code>fizzbuzz</code>.</li><li>Thread D will call&nbsp;<code>number()</code>&nbsp;which should only output the numbers.</li></ol>



<p><strong>Solution:</strong></p>



<p>4 Semaphores </p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Semaphore {
public:
  Semaphore (int count = 0): count_(count) {}

  inline void notify() {
    unique_lock&lt;std::mutex&gt; lock(mtx_);
    count_++;
    cv_.notify_one();
  }

  inline void wait() {
    unique_lock&lt;std::mutex&gt; lock(mtx_);
    while (count_ == 0) cv_.wait(lock);
    count_--;
  }

private:
  mutex mtx_;
  condition_variable cv_;
  int count_;
};

class FizzBuzz {
private:
  int n;
  Semaphore sn;
  Semaphore s3;
  Semaphore s5;
  Semaphore s15;
  

public:
  FizzBuzz(int n): n(n), sn(1), s3(0), s5(0), s15(0) {}
  
  void fizz(function&lt;void()&gt; printFizz) {
    for (int i = 3; i &lt;= n; i += 3) {
      if (i % 5 == 0) continue;
      s3.wait();
      printFizz();      
      sn.notify();
    }
  }
  
  void buzz(function&lt;void()&gt; printBuzz) {
    for (int i = 5; i &lt;= n; i += 5) {
      if (i % 3 == 0) continue;
      s5.wait();
      printBuzz();      
      sn.notify();
    }
  }
  
  void fizzbuzz(function&lt;void()&gt; printFizzBuzz) {
    for (int i = 15; i &lt;= n; i += 15) {
      s15.wait();
      printFizzBuzz();      
      sn.notify();
    }
  }

  void number(function&lt;void(int)&gt; printNumber) {
    for (int i = 1; i &lt;= n; ++i)
      if (i % 15 == 0) { s15.notify(); sn.wait(); }
      else if (i % 5 == 0) { s5.notify(); sn.wait(); }
      else if (i % 3 == 0) { s3.notify(); sn.wait(); }
      else { printNumber(i); }    
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1195-fizz-buzz-multithreaded/">花花酱 LeetCode 1195. Fizz Buzz Multithreaded</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-1195-fizz-buzz-multithreaded/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1117. Building H2O</title>
		<link>https://zxi.mytechroad.com/blog/concurrent/leetcode-1117-building-h2o/</link>
					<comments>https://zxi.mytechroad.com/blog/concurrent/leetcode-1117-building-h2o/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 25 Jul 2019 16:34:24 +0000</pubDate>
				<category><![CDATA[Concurrent]]></category>
		<category><![CDATA[concurrent]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[semaphore]]></category>
		<category><![CDATA[thread]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5354</guid>

					<description><![CDATA[<p>There are two kinds of threads,&#160;oxygen&#160;and&#160;hydrogen. Your goal is to group these threads to form water molecules.&#160;There is a barrier where each thread has to&#160;wait&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1117-building-h2o/">花花酱 LeetCode 1117. Building H2O</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>There are two kinds of threads,&nbsp;<code>oxygen</code>&nbsp;and&nbsp;<code>hydrogen</code>. Your goal is to group these threads to form water molecules.&nbsp;There is a barrier where each thread has to&nbsp;wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given a&nbsp;<code>releaseHydrogen</code>&nbsp;and&nbsp;<code>releaseOxygen</code>&nbsp;method respectfully, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must be able to immediately bond with each other to form a water molecule.&nbsp;You must guarantee that all the threads from one molecule bond&nbsp;<em>before</em>&nbsp;any other threads from the next molecule do.</p>



<p>In other words:</p>



<ul><li>If an oxygen thread arrives at the barrier when no hydrogen threads are present, it has to wait for two hydrogen threads.</li><li>If a hydrogen thread arrives at the barrier when no other threads are present, it has to wait for an oxygen thread and another hydrogen thread.</li></ul>



<p>We don’t have to worry about matching the threads up explicitly; that is, the threads do not necessarily know which other threads they are paired up with. The key is just that threads pass the barrier in complete sets; thus, if we examine the sequence of threads that bond and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.</p>



<p>Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.</p>



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



<pre class="wp-block-preformatted; crayon:false"><strong>Input: </strong>"HOH"
<strong>Output: </strong>"HHO"
<strong>Explanation:</strong> "HOH" and "OHH" are also valid answers.
</pre>



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



<pre class="wp-block-preformatted; crayon:false"><strong>Input: </strong>"OOHHHH"
<strong>Output: </strong>"HHOHHO"
<strong>Explanation:</strong> "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li>Total length of input string will be 3<em>n</em>, where 1 ≤&nbsp;<em>n</em>&nbsp;≤ 30.</li><li>Total number of&nbsp;<code>H</code>&nbsp;will be 2<em>n</em>&nbsp;in the input string.</li><li>Total number of&nbsp;<code>O</code>&nbsp;will&nbsp;be&nbsp;<em>n</em>&nbsp;in the input&nbsp;string.</li></ul>



<h2><strong>Solution: Semaphore</strong></h2>



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

<pre class="crayon-plain-tag">class Semaphore {
public:
    Semaphore(int s) : s_(s) {}

    void P(int d = 1) {
      unique_lock&lt;mutex&gt; lock(m_);
      while (s_ &lt; d) {
        cv_.wait(lock);
      }
      s_ -= d;
    }
  
    void V(int d = 1) {      
      unique_lock&lt;mutex&gt; lock(m_);
      s_ += d;      
      cv_.notify_all();
    }
private:
  mutex m_;
  condition_variable cv_;
  int s_;
};

class H2O {
public:
    H2O():s_h_(2), s_o_(2) {  }

    void hydrogen(function&lt;void()&gt; releaseHydrogen) {      
      s_h_.P();
      releaseHydrogen();
      s_o_.V();
    }

    void oxygen(function&lt;void()&gt; releaseOxygen) {
      s_o_.P(2);      
      releaseOxygen();
      s_h_.V(2);
    }
private:
  Semaphore s_h_;
  Semaphore s_o_;
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/concurrent/leetcode-1117-building-h2o/">花花酱 LeetCode 1117. Building H2O</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-1117-building-h2o/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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-663a17f809f9c180603503/] 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>
