SlideShare uma empresa Scribd logo
1 de 87
Thread Blocking Is Evil
Game Network Component Team
          Kim, J.H.
CONCURRENCY
Why is
Thread Blocking
  a Concern?
“The Free Lunch
   is OVER.”


                Herb Sutter
             December 2004
Clock speed
Execution optimization
Cache
Hyperthreading
Multicore
Cache
Write Multithreaded
    Application
CONCURRENCY
Waiting in Line
Thread
Blocking
Starvation



             Deadlock
Starvation
Task A           Task B
1: Lock          1: Sleep 0 msec
2: Sleep 1msec
3: Unlock
1000
Process time(ms)




                   995

                                                                    Task B
                   990
                                                                    Task A

                   985
                          1   2   3   4     5       6   7   8   9


                                      # of Thread
Deadlock
 Hold & Wait
Thread A                         Thread B
1A: Lock                         1B: Lock
2A: Request                      2B: Send Response
3A: Wait for Response            3B: Unlock
4A: Do something with Response
5A: Unlock
Thread A                         Thread B
1A: Lock                         1B: Lock
2A: Request                      2B: Send Response
3A: Wait for Response            3B: Unlock
4A: Do something with Response
5A: Unlock
My
Problem
Framework for
Lobby-Room style
     Game
Remote Procedure Call
Easy to write code
  because it’s all
contained inside one
      function.
‘Enter Room’ RPC          ‘Authentication’ RPC
Game Client                      Room                          Lobby
Game Client                           Room                               Lobby

              Call ‘Enter Room’ RPC

                                             Call ‘Authentication’ RPC           ‘Authentication
              ‘Enter Room’
                                                                                     RPC ‘
              RPC function
                                                                                  Function body
                  body                       Return ‘Authentication’ RPC



              Return ‘Enter Room’ RPC
Game Client                           Room                               Lobby

              Call ‘Enter Room’ RPC

                                             Call ‘Authentication’ RPC

              ‘Enter Room’                                                       ‘Authentication
              RPC function                                                           RPC ‘
                  body                                                            Function body

                                             Return ‘Authentication’ RPC


              Return ‘Enter Room’ RPC
Game Client                           Room                               Lobby



      Response Delay
              Call ‘Enter Room’ RPC

                                             Call ‘Authentication’ RPC




     From Lobby Server
              ‘Enter Room’                                                       ‘Authentication
              RPC function                                                           RPC ‘
                  body                                                            Function body

                                             Return ‘Authentication’ RPC


              Return ‘Enter Room’ RPC
Game Client                           Room                               Lobby



       Response Delay
              Call ‘Enter Room’ RPC

                                             Call ‘Authentication’ RPC




     From Lobby Server
              ‘Enter Room’                                                       ‘Authentication
              RPC function                                                           RPC ‘
                  body                                                            Function body


        Room Server
              Return ‘Enter Room’ RPC
                                             Return ‘Authentication’ RPC




     throughput Decline
What is the
Axis of Evil?
Game Client                           Room                               Lobby

              Call ‘Enter Room’ RPC

                                             Call ‘Authentication’ RPC

               Thread
               Blocking                      Return ‘Authentication’ RPC



              Return ‘Enter Room’ RPC
Inherent Limitation
      of RPC
Easy to write code
  because it’s all
contained inside one
      function.
Can not split code
  because it’s all
contained inside one
      function.
RPC::Result* JoinRoom(…)
{
   …
   RPC::Result answer = RPC::SyncCall(“VerifyLobbyUserToken”, …);
   ….
   return result;
}
What We Want
RPC Function Body


  Non-Blocking
What is the
Essence of
Problems?
Request & Wait
Solution
Asynchronous
Programming
Request(callback, …)
Pros:
Non-Blocking
Cons:
Can’t Write Sequential Code
Can’t Use Stack Variable
Can’t Split Programming Construct
…
Too Difficult!!
Coroutine
Similar to Thread
Line of Execution
Stack
      &
Local Variable
But
Non-preemptive
Instruction:
Yield
Yield Break
Resume
Who does provide
  Coroutine?
C#
      Erlang
      Haskell
JavaScript(since 1.7)
        Lua
        Perl
 Python(since 2.5)
       Ruby
         …
What about C++?
On Your Own!
Windows: Fiber

Linux:
getcontext/setcontext
makecontext
swapcontext
Asynchronous
Programming
      +
  Coroutine
Non-Blocking
      &
    Writing
Sequential Code
Solution
   for
Starvation
Before

Task A           Task B
1: Lock          1: Sleep 0msec
2: Sleep 2msec
3: Unlock
After

Task A                                 Task B
Thread A                               1: Sleep 0msec
1: Create & Resume   Coroutine
                     2: Request Lock
                     3: Yield          Non-Blocking
Thread A’
4: Resume
                     5: Sleep 2msec
                     6: Yield Break
7: Unlock
                                Sequential
                                  Code
Before




                            1000
Process time(ms)




                            995

                                                                             Task B
                            990
                                                                             Task A

                            985
                                   1   2   3   4     5       6   7   8   9


                                               # of Thread
After




                           1500
Process time(ms)




                           1000

                                                                            Task B
                           500
                                                                            Task A

                             0
                                  1   2   3   4     5       6   7   8   9


                                              # of Thread
Solution
    for
Deadlock
 Hold & Wait
Before

Thread A                         Thread B
1A: Lock                         1B: Lock
2A: Request                      2B: Send Response
3A: Wait for Response            3B: Unlock
4A: Do something with Response
5A: Unlock
After

Thread A                                    Thread B
1A: Lock                                    1B: Lock
2A: Create & Resume     Coroutine           2B: Send Response
                        3A: Request         3B: Unlock
                        4A: Yield           Non-Blocking
5A: Unlock
Thread A’
(invoked by response)

6A’: Lock
7A’: Resume
                        8A’: Do something
                        with response
                        9A’: Yield Break
10A’: Unlock
                                Sequential
                                  Code
Solution
    for
My Problem
Game Client                           Room                               Lobby

              Call ‘Enter Room’ RPC

                                             Call ‘Authentication’ RPC

               Thread
               Blocking                      Return ‘Authentication’ RPC



              Return ‘Enter Room’ RPC
Before

Room Thread                              Lobby Service
1R: Call ‘Authentication’ RPC function   1L: Process the request
2R: Wait for the response                2L: Send back the response
3R: Process
After

Room Thread                                Lobby Service
1R: Create & Resume     Coroutine          1L: Process the request
                        2R: Request        2L: Send back the response
                        3R: Yield          Non-Blocking
Room Thread’
(invoked by response)

4R’: Resume
                        5R’: Process
                        6R’: Yield Break


                                Sequential
                                  Code
Request & Wait

Request & Yield
Non-Blocking
      &
    Writing
Sequential Code
Coroutine
(Fiber)
                                      User-mode Scheduling
                                    Kernel-mode Scheduling
Thread




            CPU   CPU   CPU   CPU
RPC
Coroutine
                              Execution
  Pool
                             Thread Pool



            RPC Task Queue



             Network I/O
             Thread Pool
Network I/O             RPC Task             RPC Execution                                      Coroutine
      Thread                Queue                  Thread                                            Pool
Network
 Event             task
                 enqueue                task
                                      dequeue
                                                                   acquire coroutine
                                                                                       coroutine
                                                                     RPC
                                                          start    Execution



                                                          yield return
Network          resume
 Event             task               resume
                 enqueue
                                        task
                                      dequeue
                                                          resume



                                                           yield break

                                                                   release coroutine                           pooling
Network I/O             RPC Task             RPC Execution                  RPC Execution                  Coroutine
      Thread                Queue                 Thread 1                       Thread 2                       Pool
Network
 Event             task
                 enqueue                task
                                      dequeue
                                                                   acquire coroutine
                                                                                               coroutine
                                                                     RPC
                                                         resume    Execution



                                                          yield return
Network          resume
 Event             task               resume
                 enqueue
                                        task
                                      dequeue
                                                                           resume



                                                                         yield break

                                                                                          release coroutine               pooling
RPC::Result* JoinRoom(…)
{
   …
   RPC::Result answer = RPC::SyncCall(“VerifyLobbyUserToken”, …);
   ….
   return result;
}
RPC::Result* JoinRoom(…)
{
   …
   RPC::Result answer = RPC::SyncCallYield(“VerifyLobbyUserToken”, …);
   ….
   return result;
}
T                 Blocking

P                 Yield


S


    # of Thread
Wrap-up
“The free lunch
  is OVER.”
   Write Multithreaded
        Application
       CONCURRENCY
Thread Blocking is Evil

  Starvation   Deadlock
Asynchronous
Programming
      +
  Coroutine
Non-Blocking
      +
    Writing
Sequential Code
Request & Wait

Request & Yield
Inspired by
  Jeffrey Richter
 ‘Simplified APM With
The AsyncEnumerator’
Pictures from
www.Istockphoto.com
www.Flickr.com

Mais conteúdo relacionado

Último

Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Último (20)

TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4j
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptxBT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 

Destaque

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Thread Blocking is Evil