<?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>multithreading Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/multithreading/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/multithreading/</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>multithreading Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/multithreading/</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 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-663a17ebee16c486034501/] 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>
