Stackless Python in EVE Kristján Valur Jónsson CCP Games inc.

Slides:



Advertisements
Similar presentations
Deadlocks, Message Passing Brief refresh from last week Tore Larsen Oct
Advertisements

Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
6/13/20151 CS 160: Lecture 13 Professor John Canny Fall 2004.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
Threads 1 CS502 Spring 2006 Threads CS-502 Spring 2006.
Based on Silberschatz, Galvin and Gagne  2009 Threads Definition and motivation Multithreading Models Threading Issues Examples.
Threads CSCI 444/544 Operating Systems Fall 2008.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Fundamentals of Python: From First Programs Through Data Structures
Scheduler Activations Jeff Chase. Threads in a Process Threads are useful at user-level – Parallelism, hide I/O latency, interactivity Option A (early.
Programming Network Servers Topic 6, Chapters 21, 22 Network Programming Kansas State University at Salina.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Introduction to Threads CS240 Programming in C. Introduction to Threads A thread is a path execution By default, a C/C++ program has one thread called.
A Revolutionary Programming Pattern that Will Clean up your Code : Coroutines in C++ David Sackstein ACCU 2015.
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
Concurrent Programming. Concurrency  Concurrency means for a program to have multiple paths of execution running at (almost) the same time. Examples:
Stackless Python: programming the way Guido prevented it intended.
REVIEW OF COMMONLY USED DATA STRUCTURES IN OS. NEEDS FOR EFFICIENT DATA STRUCTURE Storage complexity & Computation complexity matter Consider the problem.
Threaded Programming in Python Adapted from Fundamentals of Python: From First Programs Through Data Structures CPE 401 / 601 Computer Network Systems.
Middleware Services. Functions of Middleware Encapsulation Protection Concurrent processing Communication Scheduling.
Discussion Week 2 TA: Kyle Dewey. Overview Concurrency Process level Thread level MIPS - switch.s Project #1.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th edition, Jan 23, 2005 Chapter 4: Threads Overview Multithreading.
1 VxWorks 5.4 Group A3: Wafa’ Jaffal Kathryn Bean.
Processes, Threads, and Process States. Programs and Processes  Program: an executable file (before/after compilation)  Process: an instance of a program.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
Code Development for High Performance Servers Topics Multithreaded Servers Event Driven Servers Example - Game Server code (Quake) A parallelization exercise.
Embedded Real-Time Systems Processing interrupts Lecturer Department University.
Multithreading vs. Event Driven in Code Development of High Performance Servers.
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
Tutorial 2: Homework 1 and Project 1
Chapter 4 – Thread Concepts
Chapter 3: Windows7 Part 5.
OPERATING SYSTEM CONCEPT AND PRACTISE
Chapter 4: Threads.
Threaded Programming in Python
Chapter 3: Process Concept
CS 6560: Operating Systems Design
Topics Covered What is Real Time Operating System (RTOS)
Chapter 4 – Thread Concepts
CS399 New Beginnings Jonathan Walpole.
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Operating System (013022) Dr. H. Iwidat
Chapter 3: Process Concept
Chapter 4: Threads.
Chapter 3: Windows7 Part 5.
Chapter 4: Threads.
Multithreading.
Multithreaded Programming
Threads and Concurrency
Threads Chapter 4.
CSCE 313 – Introduction to UNIx process
CHAPTER 4:THreads Bashair Al-harthi OPERATING SYSTEM
Threads Chapter 5 2/17/2019 B.Ramamurthy.
Threads Chapter 5 2/23/2019 B.Ramamurthy.
Still Chapter 2 (Based on Silberchatz’s text and Nachos Roadmap.)
Chapter 13: I/O Systems I/O Hardware Application I/O Interface
Chapter 3: Processes.
Chapter 4: Threads.
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
CSE 451: Operating Systems Autumn 2005 Lecture 7 Synchronization
CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization
Presentation transcript:

Stackless Python in EVE Kristján Valur Jónsson CCP Games inc.

EVE MMORPG Space game Client / server Single shard massive server active players, > concurrent users World concurrency record on a shard Relies on Stackless Python

The Tranquility cluster 400 GHz CPU / 200 Gb RAM 2 Routers (CISCO Alteon) 14 Proxy servers (IBM Blade) 55 Sol servers (IBM x335) 2 DB servers (clustered, IBM Brick x445) FastT600 Fiber, 56 x FC 15k disks, DS *EXP700 Windows 2000, MS SQL Server Currently being upgraded AMD x64

EVE Architecture COM-like basic architecture Python tighly integrated at an early stage Home-grown wrapping of BLUE objects

Stackless Python Tasklets Threads of execution. Not OS threads Lightweight No pre-emption Channels Tasklet rendezvous point Data passing Scheduling Synchronization

Stackless? No C stack Python stack in linked frame objects Tasklet switching by swapping frame chain Compromise stackless where possible. C stack whisked away if necessary

Channels

Channel semantics Send on a channel with no receiver blocks tasklet. Send on a channel with a (blocked) receiver, suspends tasklet and runs receiver immediately. Sender runs again in due course. Symmetric wrt. Send and Receive. “balance”, can have a queue of readers or writers. Conceptually similar to Unix pipes

Channel semantics, cont. Scheduling semantics are precise: A blocked tasklet is run immediately Usable as a building block: semaphores mutex critical section condition variables

Stackless in EVE BLUE foundation: robust, but cumbersome RAD Stackless Python: Python and so much more EVE is inconceivable without Stackless Everyone is a programmer

The main loop Establish stackless context int WinMain(...) { PyObject *myApp = new EveApp(); PyObject *r = PyStackless_CallMethod_Main(MyApp, “WinMain”, 0); return PyInt_AsLong( r );

PyObject* EveApp::WinMain(PyObject *self, PyObject *args) { PyOS->ExecFile("script:/sys/autoexec.py"); MSG msg; while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE)){ TranslateMessage(&msg); DispatchMessage(&msg); } for (TickIt i = mTickers.begin(; i != mTickers.end(); i++) i->mCb->OnTick(mTime, (void*)taskname); } Regular Windows message loop Runs in Stackless context The “Main Tasklet” The main loop cont.

Autoexec.py import blue def Startup(): import service srvMng = service.ServiceManager() run = ["dataconfig", "godma", “ui", …] srvMng.Run(run) #Start up the client in a tasklet! if CheckDXVersion(): import blue blue.pyos.CreateTasklet(Startup, (), {})

Tickers Tickers are BLUE modules: Trinity (the renderer) Netclient DB (on the server) Audio PyOS (special python services) …

The PyOS tick: Runs fresh tasklets (sleepers awoken elsewhere) Tick() { … mSynchro->Tick() PyObject *watchdogResult; do { watchdogResult = PyStackless_RunWatchdog( ); if (!watchdogResult) PyFlushError("PumpPython::Watchdog"); Py_XDECREF(watchdogresult); } while (!watchdogResult);

blue.pyos.synchro Synchro: Provides Thread-like tasklet utilities: Sleep(ms) Yield() BeNice()

1.Sleep: A python script makes the call blue.pyos.Sleep(200) 2.C++ code runs: 1.Main tasklet check 2.sleeper = New Sleeper(); mSleepers.insert(sleeper); PyObject *r = PyChannel_Receive(sleeper- >mChannel); 3.Another tasklet runs blue.pyos.synchro cont.

blue.pyos.synchro, ctd. 4.Main tasklet in windows loop enters PyOS::Tick() 5.mSleepers are examined for all that are due we do: mSleepers.remove(sleeper); PyChannel_Send(sleepers.mChannel, Py_NONE); 6.Main tasklet is suspended (but runnable), sleeper runs.

Points to note: A tasklet goes to sleep by calling PyChannel_Receive() on a channel which has no pending sender. It will sleep there (block) until someone sends Typically the main tasklet does this, doing PyChannel_Send() on a channel with a reader Ergo: The main tasklet may not block

Socket Receive Use Windows asynchronous file API Provide a synchronous python API. A python script calls Read(). Tasklet may be blocked for a long time, (many frames) other tasklets continue running. Do this using channels.

Receive, cont. 1.Python script runs: foo, bar = socket.Read() 2.C code executes the request: Request *r = new Request(this); WSAReceive(mSocket, …); mServe->insert( r ); PyChannel_Receive(r->mChannel); 3.Tasklet is suspended

Receive, cont. 4.Socket server is ticked from main loop 5.For all requests that are marked completed, it transfers the data to the sleeping tasklets: PyObject *r = PyString_FromStringAndSize(req->mData, req->mDataLen); PyChannel_Send(req->mChannel, r); Py_DECREF(data); delete req; 4.The sleeping tasklet wakes up, main tasklet is suspended (but runnable)

Receive completed

Main Tasklet The one running the windows loop Can be suspended, allowing other tasklets to run Can be blocked, as long as there is another tasklet to unblock it (dangerous) Is responsible for waking up Sleepers, Yielders, IO tasklets, etc. therefore cannot be one of them Is flagged as non-blockable (stackless.get_current().block_trap = True)

Channel magic Channels perform the stackless context switch. If there is a C stack in the call chain, it will magically swap the stacks. Your entire C stack (with C and python invocations) is whisked away and stored, to be replaced with a new one. This allows stackless to simulate cooperative multi- threading

Co-operative multitasking Context is switched only at known points. In Stakcless, this is channel.send() and channel.receive() Also synchro.Yield(), synchro.Sleep(), BeNice(), socket and DB ops, etc. No unexpected context switches Almost no race conditions Program like you are single-threaded Very few exceptions. This extends to C state too!

Tasklets Tasklets are cheap Used liberally to reduce perceived lag UI events forked out to tasklets A click can have heavy consequences. Heavy logic DB Access Networks access special rendering tasks forked out to tasklets. controlling an audio track “tasklet it out” Use blue.pyos.synchro.BeNice() in large loops

Example: UI Event: Main tasklet receives window messages such as WM_CLICK Trinity invokes handler on UI elements or global handler Handler “tasklets out” any action to allow main thread to continue immediately. def OnGlobalUp(self, *args): if not self or self.destroyed: return mo = eve.triapp.uilib.mouseOver if mo in self.children: uthread.new(mo._OnClick) class Action(xtriui.QuickDeco): def _OnClick(self, *args): pass

That’s all For more info: