<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Buddhika Chathuranga on Medium]]></title>
        <description><![CDATA[Stories by Buddhika Chathuranga on Medium]]></description>
        <link>https://medium.com/@vmbckscc456?source=rss-9d5093d9fab1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-G-uB0rxoKN-qvl3.</url>
            <title>Stories by Buddhika Chathuranga on Medium</title>
            <link>https://medium.com/@vmbckscc456?source=rss-9d5093d9fab1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 05:40:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vmbckscc456/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java JIT Compiler]]></title>
            <link>https://medium.com/runtimeerror/java-jit-compiler-c538e5e06a2?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c538e5e06a2</guid>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jit-compilers]]></category>
            <category><![CDATA[advanced-java]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Fri, 23 Oct 2020 20:06:36 GMT</pubDate>
            <atom:updated>2020-12-12T04:23:30.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpRapv72NBk9JbKb6c5lbw.jpeg" /></figure><p>This article will discuss the JIT (<strong>J</strong>ust <strong>I</strong>n <strong>T</strong>ime) compiler of Java virtual machine. If you are a computer science geek, you may have a good understanding of the compiler. In some cases, if you prefer to refresh your knowledge about compilers before reading this article, first read this article, which is written by me. There are two main sections in this article. In the first section, I discuss how a program is executed directly in the OS and executed in a virtual machine. In this case Java virtual machine (JVM). So if you have a good understanding of the first topic, you can directly go to the next section about the JIT compiler.</p><h3>How a program runs on the computer</h3><p>Before moving into the JIT compiler, I will discuss how the computer program works on our computer. There are two types of how we can run a program on our computer.</p><ol><li>Run the program directly on our OS</li><li>Run the program on a virtual machine that is run on our OS</li></ol><h4>Execute a program directly on OS</h4><p>First, let’s talk about executing a program directly on our OS. So imagine you have written a C code that produces prime numbers. Then you compile that code using the C compiler on your computer. This compiler will generate an executable program or a binary. You can directly run your executable on your OS. If you are running your C compiler on a Linux machine, it will generate Linux compatible executable file. If you are running your C compiler on a Windows machine, it will generate a Windows-compatible executable file. We call this a native code. Because this executable contains instructions that can run on your OS, representing the same behavior of the C code you write in your favorite IDE. So those instructions will be different according to the target OS of your compiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vTt4HDWEWYCAliuZZxKMw.jpeg" /><figcaption>How a program directly executes on OS</figcaption></figure><p>Since these instructions can run directly on your OS, it is much faster to execute the program than the second way of executing a program, executing the program on a virtual machine. Why is that?</p><h4>Execute a program inside a virtual machine</h4><p>First, let&#39;s understand what a virtual machine is. According to this analogy, the virtual machine is also a program that allows running a program (a byte code) on this machine instead of runs the program directly on OS. When we run our code on our OS directly, we call this native code, and when we run on a virtual machine, we call it byte code. JVM, the Java virtual machine, and BEAM, the Erlang virtual machine are good examples of virtual machines. So how this process happens. Let’s assume we write a Java code that will produce prime numbers. Then we can compile that Java code using the <strong>javac </strong>compiler. In the previous example, when we compile the C code using the C compiler, it generates native code that can execute directly on our OS. But when we use the <strong>javac </strong>compiler, it will generate <strong>byte code</strong> that can be run on the <strong>Java virtual machine</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnLPmp07hcqul8t-eF6ORQ.jpeg" /><figcaption>How a program execute in JVM</figcaption></figure><p>This JVM contains the JIT compiler, which is the topic of today&#39;s story. Before move into the JIT compiler, let’s try to understand how the byte code (our compiled java code) is executed inside the JVM. For this, let’s see the architecture of the JVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXfaYYCCboDILSr27tSeEg.jpeg" /><figcaption>JVM architecture</figcaption></figure><p>In the Java virtual machine (JVM), there are 3 main components.</p><ol><li>Class-Loader</li><li>Runtime Memory</li><li>Execution Engine</li></ol><p>First, the class-loader will load all the byte codes to the RAM. In that phase, JVM loads a few types of class files. Those are bootstrap classes, extension classes, and application classes. In this article, I will not talk about these in deep (But for sure, in another article about JVM). Then the byte-code inside those classes will be executed using the execution engine. The runtime memory will manage runtime data. Now the execution engine is the section that we are going to focus on.</p><p>The execution engine has a few sub-components. But a few of them are important for us in this article (bolded ones).</p><ul><li><strong>Interpreter</strong></li><li><strong>JIT Compiler</strong></li><li><strong>Profiler</strong></li><li>Garbage Collector</li><li>Java Native Interface</li><li>Native Interface Library</li></ul><p>You know how a traditional interpreter works. The same thing happens in the interpreter inside the JVM as well. It read the byte code line by line and translates into machine code, and executes it. So we can see the Java code has been executed without the JIT compiler. Then why the heck we need this JIT compiler? This is why.</p><p>Remember the C code that produces prime numbers. When we execute that code, first we compile the whole code into the machine code. Then OS can directly run that machine-code. There is no any time-cost for translations again. But when we run the Java code, the interpreter translates the byte code line by line and executes. It consumes a huge amount of time in contrast to the C code. So the JIT compiler helps to get rid of this time-consuming. The JIT compiler translates re-occurring codes into machine code. When that code phrase has occurred again, the interpreter will not translate that code phrase into machine code, again and again; instead, the machine code that is translated by the JIT compiler will be executed.</p><p>So this is how the JIT compiler works in the JVM, and in the next section, let’s see how the JIT compiler does this task and the architecture of the JIT compiler that is designed to do this task in a very efficient manner.</p><h3>The JIT compiler</h3><p>Now we know what the JIT compiler does. JIT compiler compiles re-occurring bytecode code blocks into machine code so that the interpreter can directly use that machine code. So how the JIT compiler identify these re-occurring code blocks? To figure out this, let’s analyze the architecture of the execution engine in deep. Here I will only consider the interpreter, JIT compiler, and profiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BI70ikWGE3L_BooWWc6sQ.png" /><figcaption>Java Execution engine</figcaption></figure><p>We already know the interpreter compiles the byte code line by line and executes. Profiler is the component that is responsible for identifying re-occurring byte code blocks. Refer to the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8c0f12896f3347b59b377a184536f21/href">https://medium.com/media/b8c0f12896f3347b59b377a184536f21/href</a></iframe><p>Assume this is the byte code executed by the interpreter (Unfortunately, I don’t know to write bytecode yet ☹️). When we call the executed method of JITCompiler class, it continuously calling <strong>myMethod()</strong>. So profiler can identify that this method gets called multiple times. Profiler maintaining a counter which counts the number of calls to a particular method. When it passes some threshold value predefined in JVM (You can find this value by using the <strong>CompileThreashold </strong>flag), the JIT compiler compiles that particular method into native code so that the interpreter can use that native code next time. JIT compiler does not stop its job after compiling the code into machine code. It goes even further. If that particular code block passes the next threshold value, the JIT compiler optimizes the machine code again. This happens in 4 stages. For that, there are two compilers in the JIT compiler. The <strong>C1 compiler</strong> and the <strong>C2 compiler</strong>. We also call the <strong>client compiler</strong> for the C1 compiler and the <strong>server compiler</strong> for the C2 compiler. It is not about traditional client-server architecture but about the time a Java application runs.</p><p>C1 compiler is responsible for levels 1, 2, and 3 compilations and optimizations. C2 compiler is responsible for level 4 compilation and optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WssayZu_YQ_RFjdGOuYcBA.jpeg" /><figcaption>C1 and C2 compiler of JIT compiler in JVM</figcaption></figure><p>Still, this is not the end. JVM tries to optimize the time even more. There is a memory area called <strong>code cache. </strong>It is like the cache memory in our computer system. It has limited memory, and we can tune code cache with JVM flags. When some code block is called even more, then the JIT compiler moves that method into the code cache so that the interpreter can access that particular code block quickly. But the JIT compiler does not add all the codes into this code cache since it makes a tradeoff. JIT compiler is intelligent to manage this as it can gain maximum efficiency.</p><p>We can see these compilation steps with this JVM flag.</p><blockquote><strong>-XX:+PrintCompilation</strong></blockquote><p>Refer to the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7513ab62f4f27efbe610ed0838c90ade/href">https://medium.com/media/7513ab62f4f27efbe610ed0838c90ade/href</a></iframe><p>This is the output when we run the above code with the JVM flag. Since I pass 50000 as the argument to the code, it runs until it generates 50000 prime numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZLMlI_kPMm0M9jYAJy2sA.png" /><figcaption>Java code execution with JVM flag -XX:+PrintCompilation</figcaption></figure><p>In the 3rd column, you can see the stages of the code block&#39;s compilation process. Some are in level 0, which are not compiled by the JIT compiler. That means code blocks that are not re-occurred. Some code blocks are in levels 1,2, and 3, which are compiled by the C1 compiler, and some are in level 4, which are compiled by the C2 compiler. If you see the above image carefully, you can see in the 2nd column, and there is the percentage(%) symbol in front of some code blocks. That means those code blocks are in the code cache. Since I have passed 50000 as the argument to the above program, it runs until it generates 5000 prime numbers. So the <strong>isPrime() </strong>method gets called many times. Thus, the JIT compiler has moved it to the code cache so that the interpreter can execute that method even quickly.</p><p>This is how the JVM gains the efficiency back, losing by running Java code on the virtual machine. In this article, I have talked about the process of the JIT compiler in brief. There are a lot more things that happen inside the JIT compiler and the JVM. I guess I will be able to write about those things soon. In this article, there may be a lot of mistakes that I have made. So I truly appreciate your comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c538e5e06a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/java-jit-compiler-c538e5e06a2">Java JIT Compiler</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the Compiler]]></title>
            <link>https://medium.com/runtimeerror/what-is-the-compiler-62c595a828c9?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/62c595a828c9</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[compiler-optimization]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[compiler-design]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Thu, 08 Oct 2020 09:30:12 GMT</pubDate>
            <atom:updated>2020-10-09T03:06:00.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pPYIuzHuN1cvUUKZAP__w.jpeg" /><figcaption>Image from pexels.com</figcaption></figure><p>If you are a programmer, definitely you may have heard the word <strong>compiler. </strong>But, do you know what actually the compiler is? Do you ever think what happens under the hood when you run the <strong>javac </strong>command(If you have code in Java)? Did you ever want to build your own programming language? and just create a useless GitHub repository to build your own programming language and still there is the only readme.md file, because you don’t even know where to start. I guess this should be the start, <strong>learn about the compiler.</strong></p><p>So in this article, we are going to figure out what the compiler is. If you are an experienced programmer who knows every little detail about what the compiler is, I am sorry, this is not for you. But if you are the guy in the above paragraph, follow me, let&#39;s get into the rabbit hole. Throughout this article, I will discuss the following sub-topics.</p><ul><li>Introduction to the compiler</li><li>Types of compilers</li><li>Compiler architecture</li></ul><p>At the end of this article, I wish you will be able to understand what happens under the hood when you run the <strong>javac </strong>command and you will get some idea how to write your own programming language.</p><h3>Introduction</h3><blockquote>A compiler is nothing but a source-code translator.</blockquote><p>The job of a compiler is, translate the source code from one language to another language. That means if you feed a <strong>Java </strong>source code to a compiler you can get a <strong>Python </strong>source code (Not the best example, just get the sentiment. You actually get the Java byte code which is runnable on JVM). To execute this process, the compiler has multiple components that are interconnected.</p><h3>Types of Compilers</h3><p>We can classify compilers in different ways. In this article, I will talk about two ways of classifying compilers. However, in this article, I will not go deep about compiler classification.</p><h4>Classify the compilers according to the stages of the compiler</h4><p>Here we consider the number of stages in the compiler. Some compilers directly transform high-level source code into machine code and some compilers first transform high-level source code into an intermediate representation (IR) before transforming into machine code. Likewise, we can see three types of compilers according to this classification.</p><ol><li>One-pass compilers</li><li>Two-pass compilers</li><li>Multi-pass compilers</li></ol><p>If you want to learn more about this classification of compilers, <a href="https://www.guru99.com/compiler-design-tutorial.html#3">read this article</a> on guru99.com.</p><h4>Classify compilers according to source code and target code.</h4><p>Compilers have different approaches to transform the source code into the target-code. Some compilers transform high-level language into machine language. Some compilers transform high-level language into another high-level language. Likewise, we can identify a few types of compilers according to this classification.</p><ol><li>Cross compilers — These compilers run on some platform and produce code to run on another platform. As an example, the compiler runs on <strong>platform X</strong> and produces code to run on <strong>platform Y</strong>. Embedded system developers are using such compilers.</li><li>Traditional compilers — We are most familiar with this type of compilers. These compilers transform high-level language source code into machine language source code. GCC compiler transforms <a href="https://en.wikipedia.org/wiki/GNU_Compiler_Collection#Languages">these languages</a> into low-level languages that are run on <a href="https://en.wikipedia.org/wiki/GNU_Compiler_Collection#Architectures">these platforms</a>.</li><li>Transpilers — Transpilers transform high-level language source code into another high-level language source code. As an example, the Babel transpiler converts ECMAScript 2015+ into JavaScript.</li><li>Decompiler — Decompiler takes low-level source code as the input and attempts to create high-level source code which can be recompiled successfully.</li></ol><h3>Compiler Architecture</h3><p>When a compiler compiles(translate) the source code, it will go through several phases. See the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/0*yZHowHzaWx-gtlUH.png" /><figcaption>Diagram from Javatpoint.com — <a href="https://www.javatpoint.com/compiler-phases">https://www.javatpoint.com/compiler-phases</a></figcaption></figure><p>We can divide all the phases into two phases as <strong>front-end </strong>and <strong>back-end</strong>. Front-end and back-end include the following phases.</p><h4>Front End</h4><ul><li>Lexical analyzing</li><li>Syntax analyzing</li><li>Semantic analyzing</li><li>Intermediate code generation</li></ul><h4>Back End</h4><ul><li>Code optimization</li><li>Code generation</li></ul><p>In the next section, I will briefly describe what happens in each phase. If you are not a compiler programmer, then it’s okay to know what happens in each phase briefly. But if you want to design a compiler, then you have to have a better understanding of what’s happening in each phase.</p><h4>Lexical analyze</h4><p>Now you know the compiler is a program that transforms source code into another source code. The compiler gets the source code as a file. That file contains the code in text format. But compiler can not work with this text. It has to convert this text into some format that the compiler understands. For that what the compiler does is, break the text into tokens. Remember that these token are pre-defined in language grammar. This token will be useful in the next phases of the compiling process. See the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WI4fX1K28lXJVotu.png" /><figcaption>Diagram from <a href="http://quex.sourceforge.net/">http://quex.sourceforge.net</a></figcaption></figure><p><strong>KEYWORD, BRACKET, IDENTIFIER, OPERATOR, NUBER </strong>in the above diagram are tokens. The compiler uses lexical analysis to identify these tokens and if it gets a token that is not pre-defined in language grammar, then it will be considered as an error.</p><h4>Syntax analyzing (Parsing)</h4><p>In this phase what the compiler does is check whether those identified tokens are arranged in the correct order. To check this every language has a rule set called <strong>Grammar</strong>. First, the compiler attempt to build a data structure called a parse tree. If the compiler could build the parse tree successfully according to the pre-defined rules in grammar, then there are no syntax errors in the source code. Otherwise, there are errors and the compiler will show those syntax errors. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axQW6iJzlvhbltkEiepcnw.png" /></figure><p>Here we have defined a grammar. Then the compiler attempts to build the parse tree for the source code <strong>2 + 3 * 3</strong>. In this case, the compiler can build the parse tree on the right side successfully according to the grammar, so there are no syntax errors in this program.</p><h4>Semantic analyzing</h4><p>Just because a program has no syntax errors, the compiler can not assume the code is correct. Consider the sentence below.</p><blockquote><strong>I love compilers</strong></blockquote><p>Now let&#39;s assume all the words in this sentence are correct tokens identified in the lexical analyzing stage. As humans, we know in English sentence there is an order <strong>Subject -&gt; Verb -&gt; Object.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wATxZcL6ZjVYjq-QNMBNOA.png" /></figure><p>In syntax, analyzing phase compiler can decide there are no syntax errors in this sentence because tokens (words) are arranged in the correct order.</p><p>Now consider the sentence below.</p><blockquote>I eat compilers</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VS4giznBJTT3gzjMhwETDA.png" /></figure><p>Let&#39;s assume <strong>eat </strong>is a correct token according to the grammar. So this sentence is correct sentence according to the lexical analysis phase and also correct according to the syntax analysis phase since the word is arranged in the correct order. But there is <strong>NO MEANING </strong>in this sentence. Because <strong>No one can eat compilers (</strong>rather than novice compiler programmers like me 😅)</p><p>So according to the semantic analysis phase, this program has errors. We call that semantic errors. Refer to this simple Java code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/279281b11956a231e301de2fd5aa978d/href">https://medium.com/media/279281b11956a231e301de2fd5aa978d/href</a></iframe><p>In this code, there are no syntax errors. All token are ordered correctly. But in the line 5 <strong>int total = c + d; </strong>has no meaning, since identifiers <strong>c </strong>and <strong>d </strong>are <strong>undefined. </strong>These types of errors are semantic errors. The compiler can catch semantic errors in the semantic analysis phase.</p><h4>Intermediate code generation</h4><p>Any compiler can directly generate machine code from source code. So why we need an intermediate code generation phase? There are different types of machines. So the machine code is system dependant, while the high-level source code does not. If the compiler directly generates machine code from the source code, every machine needs a complete front to back compilers. But when the compiler generates intermediate code (we call this <strong>Intermediate representation</strong>) it can generate machine code for each machine using intermediate code, without lexical analyzing and parsing again and again for each machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SU_BTjAdFFlaadNw-XJLzw.png" /></figure><p>There are two major types of Intermediate representations.</p><ol><li>High-level IR — More close to high-level language</li><li>Low-level IR — More close to machine code</li></ol><p>There are few ways of representing the intermediate representation.</p><ul><li>AST — Abstract syntax tree (Graphical)</li><li>Postfix notation</li><li>Three address code</li><li>Two address code</li></ul><h4>Code optimization</h4><p>The code optimization phase performs two main things. Reduce the <strong>time</strong> or reduce the <strong>resources</strong>. What is the meaning of this? When a user writes code, there is nothing but instructions. When the CPU executes these instructions it takes time and resources (memory). So the purpose of the code optimizing phase is to reduce the execution time and resources consumed by the program. Code optimizer always follows three rules.</p><ol><li>The output code must not, in any way change the meaning of the source code.</li><li>Either reduce the time or resources or both</li><li>The code optimizing phase will not take a long-time itself and make the whole compiling process slow</li></ol><p>There are two ways of code optimization.</p><ol><li>Machine-independent optimization</li><li>Machine-dependent optimization</li></ol><p>Machine-independent optimization takes the intermediate representation as to the input and does not care about any CPU registers and memory locations. This happens after the intermediate code generation phase.</p><p>In machine-dependent code optimization, the compiler does care about CPU registers, memory locations, and architecture of the machine. This happens after the machine code generation phase.</p><h4>Code generations</h4><p>Code generation is the last phase of the compiling process. There may be machine-dependent code optimizations as well. But we can consider both together as code generation. In this phase, the compiler generates a machine-dependent code. The code generator should have an understanding of the runtime environment of the target machine and its instruction set.</p><p>In this phase, the compiler performs a few major tasks</p><ul><li>Instructions selection — Which instruction to use</li><li>Instruction scheduling — In which order the instructions should be ordered</li><li>Register allocation — Allocate variables into the processor registers</li><li>Debug data — With debug data code can be debugged</li></ul><p>The final machine-code generated by the code generator can be executed on the target machine. This is how the high-level source code that we write on our favorite editor transforms into a format that could be run on any target machine.</p><p>In this article, I have described all the phases brief. If you want to go deep in these concepts, you can find millions of resources out there on the internet.</p><p>So I hope you gathered new knowledge to your knowledge pool. If there is any mistake or some unclear point, please don’t hesitate to comment below. Thank you all and here are some valuable resources that I used to write this article.</p><ul><li><a href="https://en.wikipedia.org/wiki/Compiler">https://en.wikipedia.org/wiki/Compiler</a></li><li><a href="https://web.stanford.edu/class/archive/cs/cs143/cs143.1128/">https://web.stanford.edu/class/archive/cs/cs143/cs143.1128/</a></li><li><a href="https://www.javatpoint.com/compiler-tutorial">https://www.javatpoint.com/compiler-tutorial</a></li><li><a href="https://www.tutorialspoint.com/compiler_design/index.htm">https://www.tutorialspoint.com/compiler_design/index.htm</a></li><li><a href="https://www.guru99.com/compiler-design-tutorial.html">https://www.guru99.com/compiler-design-tutorial.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62c595a828c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/what-is-the-compiler-62c595a828c9">What is the Compiler</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GSoC 2020 — Community Bonding Period]]></title>
            <link>https://medium.com/runtimeerror/gsoc-2020-community-bonding-period-4bae81bb053f?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bae81bb053f</guid>
            <category><![CDATA[gsoc-2020]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 06:17:28 GMT</pubDate>
            <atom:updated>2020-06-22T06:17:28.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>GSoC 2020 — Community Bonding Period</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdJRWN6EydIrJH-zI-eD3g.jpeg" /><figcaption>Download from <a href="https://www.pexels.com/photo/focus-photo-of-4-wooden-pawn-figurine-209728/">https://www.pexels.com/photo/focus-photo-of-4-wooden-pawn-figurine-209728/</a></figcaption></figure><p>GSoC 2020 community bonding period has come and gone. It took a long time for me to finish my article. However, this is an update about my community bonding period. If you don’t know how GSoC happens, then let me explain what the community bonding period is. So what happens here is we are getting ready to start the implementation of our GSoC project. There are several things to be done in this period.</p><ul><li><strong>Setup the repository</strong> — If you are working on a new project then you have to create a repository for your project in your organization. If you are working in an existing project then your organization admin will add you to the organization and the repository.</li><li><strong>Get to know your mentor</strong> — You can use this period to get familiar with your mentors. You may have different time zones and you can discuss comfortable time slots for both of you and any other things related to the project.</li><li><strong>Set up communication channels</strong> — You will have millions of things to discuss with your mentors and org admins throughout this project. So it will help if you can discuss and fix your communication channels before starting the coding phase. In my case, we had Gitter channels to communicate and in Jenkins, they have nicely organized chat communication channels. So it was really easy for me to set up in those communication channels. Also, you must take a meeting weekly with your mentors. So its better if you can fix that as well.</li><li><strong>Getting familiar with the code-base</strong> — You can use the community bonding period to get familiar with the code-base. Also if you have enough time it’s better to create one or two pull requests in this period as well. It may or may not be related to your project. But both cases will help you to get to familiar with the code-base. In my case, as I mentioned in <a href="https://medium.com/runtimeerror/path-to-gsoc-2021-e6a81e62308d">Path to GSoC — 2021</a>, I started contributing to this project even before the application period began. So it helped me to get familiar with the code-base.</li><li><strong>Creating tasks </strong>— You can create the tasks that you are going to finish during the coding phase. You can use a project management tool that you prefer. Most of the time there are some default project management tools in your organization. You can use that as well. You can discuss this with your organization.</li></ul><p>If you have done all the things I have mentioned, then you are almost ready to start the coding phase. There may be some other things to be done according to your organization. For example, I had to update my project on the <a href="https://www.jenkins.io/projects/gsoc/2020/projects/winsw-yaml-configs/">Jenkins</a> website. Also, you can discuss your timeline and also about the deliverables, that you are going to do during the coding phases. It’s always okay to do changes in your timeline with the help of your mentor.</p><p>As I mentioned before if you have done all these things and still you have free time it’s okay to start coding. In my case, I started working on a task, which is not directly related to my project. I had to extract and feed configurations from a YAML file. In this period what I did is validating the XML configuration file. It helps to understand my project as well and my mentor helps me a lot to direct me the correct path.</p><p>So those are the updates about my community boding period and let’s meet with a blog post on the Coding phase soon. Good Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bae81bb053f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/gsoc-2020-community-bonding-period-4bae81bb053f">GSoC 2020 — Community Bonding Period</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Path to GSoC-2021]]></title>
            <link>https://medium.com/runtimeerror/path-to-gsoc-2021-e6a81e62308d?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a81e62308d</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[windows-services]]></category>
            <category><![CDATA[gsoc-2020]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Wed, 06 May 2020 18:18:44 GMT</pubDate>
            <atom:updated>2020-05-06T18:18:44.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8_HupL-u2tehE2LFf3uXw.jpeg" /></figure><p>Well, this is one article that I’ve been pretty excited to write about! Today, I am going to talk about how to get selected into GSoC-2021. I know most of you are looking forward to participating in GSoC, but don’t know how to start. So here’s a little guidebook for you. [🔴 <strong>Warning</strong> 🔴] — If you have already participated in GSoC just don’t read this. This article is probably not for you! 😛</p><p>Before doing anything else, first of all, we should probably understand what GSoC is and why we should participate. Then we can talk about how we can do that.</p><h3>What is GSoC</h3><p>GSoC is simply an internship program organized by Google. There are 3 major roles in this program.</p><ol><li>Google Company</li><li>Open Source Organizations</li><li>Students ( Us 😃)</li></ol><p>All these roles have their responsibilities throughout the program and when everyone gets their job done perfectly, we say GSoC was completed successfully.</p><p>First I’ll give a very brief introduction of how the program goes. As you know there are many open source organizations and they have tons of nice projects to be done. So what simply happens is, students (that’s us!) can join them and work on those projects. When the program is finished Google will pay us and give a certificate. Now let’s take a look at what are the responsibilities of each role.</p><h4>Google Company</h4><p>Google company is the one who organizes the event. They help students to find open source organizations and projects. They also help organizations to filter out students’ proposals and finally they will be the ones paying us at the end of the internship. Usually, before summer, Google opens a portal, which contains all the projects that organizations have put up for students to do for them. So students (again, us!) can go to that portal and find a project to do. When the students finish the internship successfully, Google will pay a nice stipend.</p><h4>Organizations</h4><p>As you know now, organizations are the group that owns and hand out projects for GSoC. Apart from that, there are two other major roles to talk about.</p><ol><li>Org Admins</li><li>Project Mentors</li></ol><p>Org admins are the people who provide initial feedback from the organization’s side such as Structure of the application, compliance with applicable rules, and advising how to reach out to the community.</p><p>Project mentors are the people who are going to mentor student’s projects. They are the people who are going to be with you from the beginning to the end of the internship.</p><h4>Students</h4><p>In case you haven’t realized yet, that’s us! Our job is to go to that portal I mentioned before and select an organization and a project and submit our project proposal. If you get selected, then you need to successfully finish that project and that’s it! Yeah, I know, it’s that easy! As a student, you just need a burning desire to finish GSoC successfully.</p><p>Those are the key roles of the GSoC program, but some other topics are worthwhile knowing if you’re planning on participating. For one thing, this is not a program that ends in a week o two. This is a long term process that goes through several stages and it is very important to get to know what is happening in each stage. Let’s take a look.</p><h3>Stages of GSoC</h3><p>GSoC happens in 5 major stages. Here I will explain what is happening in each phase one by one. Usually, Google will publish the <a href="https://developers.google.com/open-source/gsoc/timeline">timeline</a> of a particular year by the beginning of the year. Then you can start working on GSoC ( Actually you can start even earlier, but more on that on my user story article ). So here are the major stages of the GSoC event.</p><ol><li>Application period</li><li>Students projects Selection period</li><li>Community Bonding period</li><li>Coding.. coding.. coding…</li><li>Final Evaluation</li></ol><p><strong>1 — Application Period</strong></p><p>This is the most important phase, so this is also the phase that I will be describing the most. In this period students are going to find appropriate projects for them, create their project proposals, and submit them. To find projects, students can go to the Summer of Code portal and they can find projects there. As I said in a later article, I will explain my user story ( I am pretty sure, that will be interesting because I was totally like you before the start ). Here I will post some screenshots so you can understand this much better. You can find the GSoC-2020 portal <a href="https://summerofcode.withgoogle.com/organizations">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7fOjy3YdHwGnYjn2q0oMQ.png" /><figcaption>GSoC-2020 Organizations</figcaption></figure><p>When you navigate to the <strong>Organizations </strong>tab you can find <strong>selected </strong>open-source organizations for that particular year. Yeas I said <strong>selected </strong>open-source organizations and that’s because just like us students, organizations also have to be selected into the GSoC event. As students, it’s not that important for us right now(But it will be later, so more on that in my user story article).</p><p>Here you can select any open-source organization to contribute. For example, my lucky organization was <strong>Jenkins. </strong>When going inside that organization you can see <strong>VIEW IDEAS LIST. (</strong>Here you can see <strong>VIEW PROJECTS </strong>because I took this screenshot after students’ projects were selected, but before the selection, you will be able to see <strong>VIEW IDEAS LIST</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1COCw0cFLHOAW7hTpgIug.png" /><figcaption>GSoC2020 — Jenkins</figcaption></figure><p>You can go inside the <strong>VIEW IDEAS LIST </strong>and you can see the project ideas on the organizations’ website and select one appropriate for you. (Remember, you can select an existing project as well as submit your project idea if you like)</p><p>As I mentioned in this stage, students have 3 key things to do.</p><ol><li>Select an organization and a project.</li><li>Create a project proposal.</li><li>Submit the proposal.</li></ol><p>Now you know how to select an organization and a project. Most of the time (usually if you’re like me that is…) you will fall into an endless rabbit hole where we can’t come out of, moving from one interesting project to the next unable to make a decision. So, I’ve got two pieces of advice for you.</p><blockquote>“If you have a busy schedule ahead, then select a project with technologies, which are already familiar with you.”</blockquote><blockquote>“If you won’t be that busy, then select a project with technologies that you want to improve or learn or the technologies which you look forward to making your future career with.”</blockquote><p>In my case, at the time I was having a pretty busy schedule since it was my final year at university. So, I ended up selecting a C# (.Net, Windows Services) project, which is familiar to me. Even on this familiar platform, I found so many interesting things to learn, so don’t think you’re missing out by picking a technology that you already know.</p><p>Then what you have to do is understand the project well and create a proposal for the project which contains how you are going to develop it.<a href="https://google.github.io/gsocguides/student/writing-a-proposal"> Here you can find out how to write a better project proposal.</a> After creating your project proposal you can submit it through the portal. Here also I have some advice for you.</p><blockquote>Before submitting your proposal always remember to discuss your proposal with project mentors.</blockquote><p>You can reach out to your project mentors in their mailing lists, Gitter channels, Slack channels, etc. I will explain those things in more detail in my user experience article. Here I just want to clarify how the GSoC event happens.</p><p><strong>2 — Students’ projects Selection period</strong></p><p>In this period your organization and Google evaluate your project proposal and they will decide whether it is good enough to continue. After selecting the project proposals, they will publish selected proposals and send you an email as well. Trust me, this will be the most exciting email you are going to receive all summer! 😁</p><p><strong>3 — Community Bonding Period</strong></p><p>If you came this far, congrats! You have finished the most difficult stage. Now, it’s time to get to know the community. Here, you have to do a few things.</p><ul><li>Get to know your mentors.</li><li>Read documentation.</li><li>Setup the developing environment.</li><li>Get familiar with the codebase.</li><li>Start working on your project.</li></ul><p>When I was writing this article I was in this stage, so I don’t have many experiences regarding the other stages. But I as I mentioned before I just want to explain to you what is going on in this GSoC event, so I think my experience in those phases won’t matter just yet.</p><p><strong>4 — Coding… coding…. coding…</strong></p><p>Yeah, you got it! You are going to code in this stage. In this phase, you fill follow the project proposal that you submitted. There are three evaluation steps in this stage where you need to evaluate what you have done until then. This is when you will work with your project mentors the most.</p><p><strong>5 — Final Evaluation</strong></p><p>The third evaluation of the above stage will be this. Here you will evaluate your project and google and your selected organization will decide whether you have completed your project as you proposed. This will also be where they decide whether you have completed GSoC successfully or not. If you have, then you will get a valuable certificate from Google and you will be paid as well for your contribution.</p><p>So, this is how the GSoC event happens. There are many things I have not discussed so far, but I think this should be enough to give you a brief understanding. Now let’s talk about why you should participate in GSoC.</p><h3>Why you should participate in GSoC</h3><p>As I mentioned before, GSoC is a huge internship program for university students. The most special thing is, here you have to work with <strong>the open-source community</strong>. I don’t know much about how open source happens since I just started, but, I know that this is one of the best opportunities that you will get to start contributing to the open-source community. Here are some of the skills I’ve managed to add to my profile thank to GSoC2020 so far. (At the time of writing this article, I was in the Community bonding period)</p><ul><li><strong>Communication Skills</strong> — This is one of the most important skills that I’ve gained so far. You have to discuss continuously with your mentors about your project and also with other students who wish to participate in GSoC. Most of them are from different countries and cultures. To get selected you have to be responsible. You have to check your emails regularly (which is something I was used to skipping) and reply to them. You can answer to questions asked in mailing lists and other communication channels. So definitely you can improve your communication skills.</li><li><strong>Studying a codebase</strong> — This is another skill that you are going to add to your skill-set. To create your project proposal, first, you have to identify the problem well. Then to provide a solution, you have to study the codebase. When you are doing this, you can always get help from your mentors and who are always more than happy to lend a hand. It was a nice experience for me to see that even those experts would reply to my beginner questions without any complaint.</li><li><strong>Working on time</strong> — To get selected into GSoC, you have to work on time. Since almost everything up to this step follows their deadlines and procedures, you need to be responsible and keep working according to the given schedule.</li><li><strong>Working with an organization — </strong>This is a different experience from when you open a Github repository for your project and start coding all by your lonesome self. You have to be in sync with your team. It is really important for your career as well. You can ask questions and you can answer them too. Trust me, it’s awesome.</li></ul><p>Apart from these, I’m pretty sure there will be a lot more to learn in the other phases as well. Especially, in the coding phase, I’m certain you will get the opportunity to collect a lot of technical skills and non-technical experiences. I think these skills are the reason you should participate in GSoC. It is a huge opportunity to polish your career path and it will add so much value to your CV as well. Also, as I mentioned before, this will open the door to the Open source world, and though I don’t quite have enough experience to explain it right now, I’m pretty sure I’ll be able to sometime later in another article.</p><p>Well, that’s it for now. I hope this article was enough to pique your interest a bit. See you all in GSoC — 2021!!! 🎉 🎉 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a81e62308d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/path-to-gsoc-2021-e6a81e62308d">Path to GSoC-2021</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Switch between Wi-Fi connections using keyboard shortcuts.]]></title>
            <link>https://medium.com/runtimeerror/switch-between-wi-fi-connections-using-keyboard-shortcuts-1857396151b7?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1857396151b7</guid>
            <category><![CDATA[netsh]]></category>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <category><![CDATA[wifi]]></category>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[windows-10]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Sat, 02 May 2020 10:21:34 GMT</pubDate>
            <atom:updated>2020-05-02T12:56:52.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IR6bxbFT6IbVNUU_n44Qbg.jpeg" /></figure><p>This is totally out of my writing area, but I thought it is worthwhile enough to write. Most probably you might be using more than one internet package at the moment to connect to the internet. I do. I am using one internet connection for my work and another package for YouTube. But the problem is I always forget to switch before going to YouTube, so I waste a lot of data. Also, its just bothersome to take my mouse to the bottom of the window and change the Wi-Fi every time. So I created a keyboard shortcut to switch between Wi-Fi connections. You can do this too if you are in Windows. I had installed Windows 10 on my laptop when I did this.</p><p>Let me show you how this works. I will be using the <strong>netsh </strong>cmd utility. First, go to your desktop and create a new shortcut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*Kk6hJ1vFgWFBjAYAqgx7rg.png" /></figure><p>Then you will get a dialog box as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*HvGwbpx5XqlNzK8BZqW-Lg.png" /></figure><p>Enter this command on the text box.</p><pre>netsh wlan connect name=[ABC] ssid=[&quot;ABC&quot;]</pre><p>Here you have to enter your Wi-Fi <strong>profile name</strong> and your Wi-Fi <strong>SSID</strong>. You can find it using either the command prompt or Windows settings as shown below.</p><ol><li>Using CMD</li></ol><p>Run CMD as administrator and type this command and hit enter.</p><pre>netsh wlan show profiles</pre><p>Then you will get an output like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*CwKeHO-eMLZz0tbAvs-lTw.png" /></figure><p>These are the all <strong>Wi-Fi profiles</strong> set in my laptop. You can use one of these as the name in the above command and you should set the <strong>SSID</strong> as the SSID of the respective Wi-Fi profile</p><p>2. Using Windows Settings</p><p>First, go to your Wi-Fi settings and click <strong>Manage known networks</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkSD8by2YiBwOl8p2s-4lg.png" /></figure><p>Now you can see a window as shown below and select the Wi-Fi network you want to connect into. Then click the <strong>Properties</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ct-u4FSn7zxcEywOrxqeag.png" /></figure><p>Those names on each Wi-Fi connection are the profile names of your Wi-Fi connections. You can find it here as well 😜. When you click the <strong>Properties</strong> button you will be directed into another window. Scroll to the bottom of that window. Now you will see all the visible details of the Wi-Fi connection that you selected and you can see the SSID<strong> </strong>that you need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyKSclK2RSbc73aSUllNJw.png" /></figure><p>Now the command that you enter into the text box should be like this.</p><pre>netsh wlan connect name=SLT ssid=&quot;SLT&quot;</pre><p>Don’t forget the little inverted commas 👀. Then click next and a new dialog box will be opened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*XH4Y8c-gv9Y5A_CvxgTJOA.png" /></figure><p>Enter any name you prefer in the text box and click the <strong>Finish</strong> button.</p><p>Now you have created a simple script to change your Wi-Fi connection and the next thing to do is to set a Keyboard shortcut to this script. Right-click on the shortcut you get on the desktop and select <strong>Properties. </strong>A little dialog box will be opened and go to <strong>Advanced.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*8rghkyU9upLGLQ9IF4OWQA.png" /></figure><p>There you will see an option <strong>Run as Administrator. </strong>Select that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*js1nnvP96k-N257p3AUXcA.png" /></figure><p>Click <strong>OK. </strong>Then you have to set the Shortcut key binding. For that, first, go to the Shortcut tab and you will see a text box called <strong>Shortcut Key. </strong>Add your key binding there. <strong>You just have to press the keys that you want as your shortcut key biding.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*ZKaqmn02gjc6EWkVXR-8ug.png" /></figure><p>Then click <strong>Apply </strong>and <strong>OK. </strong>Now you have successfully created your keyboard shortcut to connect to your Wi-Fi. Using this, you can connect into one Wi-Fi network. If you have two Wi-Fi connections, then you have to create another shortcut and set the Shortcut key binding to that as well. When you set shortcut key bindings, remember to choose key bindings which are close to each other. As an example my shortcuts are,</p><p>CTRL + ALT + 1</p><p>CTRL + ALT + 2</p><p>So its easier to switch between different Wi-Fi connections. Well, that’s the whole story, now go on and enjoy the shortcuts! 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1857396151b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/switch-between-wi-fi-connections-using-keyboard-shortcuts-1857396151b7">Switch between Wi-Fi connections using keyboard shortcuts.</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inter Process Communication]]></title>
            <link>https://medium.com/runtimeerror/inter-process-communication-1c97f5798ea?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c97f5798ea</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[process]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 13:17:05 GMT</pubDate>
            <atom:updated>2020-04-22T05:15:33.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inter-Process Communication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBGahvYz6p0rmTygdUNjIA.jpeg" /></figure><p>We know that many processes are running in an operating system concurrently. Processes running concurrently means there may be two or more processes run at the same time. But the actual concurrent concept is a lot more than that and read this article to learn about the concurrency of a computer system. Now when processes run concurrently, we can identify two types of processes.</p><ul><li>Independent processes 🚶</li><li>Co-operating processes 👭</li></ul><p>Independent process means that anything happens in that process will not affect other processes that are executing and anything happens in other processes will not affect this process. Co-operative processes are processes which depend on other processes running in a computer system. Simply, co-operative processes are processes that are sharing data. That means those processes need to communicate with each other to know their states. When processes communicate with each other, we call that Inter-process<strong> communication(IPC)</strong>. It’s much simpler than you think😛</p><p>Now we know that inter-process communication is two or more processes sharing data. In a modern computer system, there are two models of doing this.</p><ul><li>Shared Memory</li><li>Message Passing</li></ul><p>In the shared memory model, processes using a shared portion of memory to communicate data. One process can write to that memory and another process can read from that memory.</p><p>In the message-passing model, the process is not using a shared memory portion. Process directly sends data to other processes, which they need to communicate with.</p><h4>Shared memory model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*xOq3lkDfnVWq_SboPSYomA.jpeg" /><figcaption>Interprocess communication — Shared memory model</figcaption></figure><p>Now we know that the shared memory model has a shared portion of memory to communicate data between processes. Let us imagine there are two processes called P1 and P2 and those processes need to communicate. Let’s say P1 needs to send some data to P2. The following steps describe how this will happen.</p><p><strong>Step 1: </strong>First P1 establish a shared memory region in P1’s address space.</p><p><strong>Step 2</strong>: Now P2 should attach that shared memory region to its address space. Then P1 writes data that needs to share with P2 in the shared memory region.</p><p><strong>Step 3</strong>: P2 reads data from the shared memory region.</p><p>Now there are a few important points that we should keep in mind about the shared memory model. As you see, always shared memory region initiate inside an address space of one process. Literally, inside the address space of the process which needs to initiate the communication. And then other processes need to attach that memory space into its memory and we know that the operating system does not allow to access the address space of a process by another process. So if a shared memory system needs to be executed, then the operating system has to remove that restriction of one process can’t access another processes address space.</p><p>We can see this model as a producer-consumer model. One process will produce the data and another process will consume the data. We call <strong>buffer</strong> to this shared memory region. When processes writing and reading using this buffer, those processes need to be synchronized well, so that the consumer process will not try to read data that the producer has not produced yet. The race condition may arise if both the processes i.e. producer process and consumer process try to access the shared data concurrently.</p><p>There are two types of buffers.</p><p><strong>1.Bound Buffer</strong></p><p>Bound buffer has a limit of size. With this type of buffer, the consumer has to wait if the buffer is empty and the producer has to wait if the buffer is full.</p><p><strong>2.Un-bound buffer</strong></p><p>There is no limit of size in this type of buffer. In this case, the consumer has to wait if the buffer is empty. But producers can always produce data since there is no limitation of the size of the buffer.</p><p>There are both pros and cons in the shared memory model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*Vm-su6xEQWB4s2A38SAtCg.png" /><figcaption>Pros and Cons of shared memory IPC</figcaption></figure><h4>Message Passing Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*jp3mxE34lPr9eDXMLSi1eA.jpeg" /><figcaption>Inter-Process Communication — Message Passing Model</figcaption></figure><p>The message-passing model provides a mechanism to allow processes to communicate and to synchronize their actions without sharing memory and this model is particularly useful in distributed systems, where the communication process resides on two computers connected by a network. Now let’s see how the message passing model works inside.</p><p>In message-passing models, there are two main operations.</p><ol><li>Send — sending a message to a process</li><li>Receive — receive a message from a process</li></ol><p>According to the size of the message, there are two types of messages in a message-passing system.</p><ol><li>Fixed-size messages</li><li>Variable size messages</li></ol><p><strong>Fix Size Message — </strong>The message has a fixed size. System-level implementation of this type is straight forward. But make the task of programming more difficult. Imagine a process that has to send a message to another process, which is bigger than the message size limit. Then the producer process has to break the message into parts and send using mechanisms like serializing. Some systems, if the data that has to pass with the message is too big, send the pointer of the data. This depends on the system design.</p><p><strong>Variable Size Message — </strong>There is no limit to the message size. System-level implementation is a bit difficult. The system has to allow any size of the message. But the programming task becomes much easier. A producer has not to worry about the size of the message.</p><p>When two processes communicating using the message-passing model, there should be a logical link between these two processes. There are various ways of creating this link logically and physically. Here we are going to talk about only how logically implement this link between processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*DLRtBhgl3mcybHFcLjmYSA.png" /><figcaption>Logical link between two processes</figcaption></figure><p>Processes can execute <strong>send()</strong> and <strong>receive() </strong>operations via this logical link. As I mentioned before there are various ways to implement this link and <strong>send()</strong>, <strong>receive() </strong>operations.</p><ul><li>Direct or Indirect Communication</li><li>Synchronous or Asynchronous Communication</li><li>Automatic or Explicit Buffering</li></ul><p>Also, there are few issues related to these implementations such as</p><ul><li>Naming issues</li><li>Synchronization issues</li><li>Buffering Issues</li></ul><p>Let’s talk about this in deep.</p><h4>Direct and Indirect Communication</h4><p><strong>Direct Communication</strong></p><p>Indirect communication model, each process must explicitly specify the sender or the receiver. See the below example.</p><pre>send(P, message)<br>receive(Q, message)</pre><p>This process sends a message to process P and receives a message from process Q. It has explicitly specified the sender and the receiver. The logical link created between these types has few properties. The link is associated with exactly two processes and there is only one link between two processes. Processes must know the producer process and consumer process. We call this <strong>symmetry in addressing</strong>. Because both the sender and the receiver have explicitly named.</p><p>There is another variety of this direct message passing.</p><pre>send(P, message)<br>receive(pid, message)</pre><p>In this case, specify only the receiver explicitly. This process sends a message to process P and receives a message from any process. We call this <strong>asymmetric in addressing</strong>.</p><p>There are some disadvantages to this direct communication model. This limits the modularity of a program. If one process reference changed, all other processes which depend on that process need to be changed.</p><p><strong>In-direct communication</strong></p><p>Indirect communication model using <strong>mailbox </strong>or <strong>ports </strong>to passing messages. The mailbox is a sort of abstraction to a memory location that is used by processes to save messages and retrieve messages. Each mailbox has a unique identification and two processes can share messages if both have a shared mailbox. The mailbox may own either by the process or the operating system. It will depend on the system implementation. Refer to this example.</p><pre>Send(A, message)<br>Receive(A, message)</pre><p>Here is the mailbox. The process can send messages to mailbox A and processes can receive a message from mailbox A. When using a mailbox more than two processes can participate in a communication channel. Because of that, some issues can occur. Refer to the below situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Do2_EP5C0KlDGTdFV1OVoQ.png" /></figure><p><strong>Process A</strong> sends a message to the mailbox and <strong>Process B</strong> and <strong>Process C</strong> can receive the message. Now the problem is who is going to receive the message among <strong>Process B</strong> and <strong>Process C</strong>. There are a variety of workarounds to prevent this issue.</p><ul><li>Allow links to be associate with two processes at most so that only two processes will communicate using the mailbox. So there will be only one receiver process at once.</li><li>Allow at most one process to execute <strong>receive() </strong>operation.</li><li>Allow the system to select, which process will receive the message. The system can use priority algorithms to select the process which will receive the message.</li></ul><h4>Synchronous or Asynchronous Communication</h4><p>We know that message passing between processes is happen using <strong>send() </strong>and <strong>receive() </strong>primitives. There are different design options for implementing each primitive. According to this design, message passing may be either <strong>blocking </strong>or <strong>non-blocking</strong>. We can call this synchronous or asynchronous. According to this blocking or non-blocking design, we can divide message passing into 4 categories.</p><ol><li>Blocking Send — The sending process is blocked until the receiving process gets the message from the mailbox.</li><li>Non-blocking send — The sending process sends the message and continues its operations. The sender doesn’t worry whether the receiver gets the message from the mailbox or not.</li><li>Blocking Receive — Receiving process blocked, until a message is available.</li><li>Non-blocking Receive — Receiving process receive either a message or null. Receive the process not to wait until the message arrives.If the message available then get the message. If the message is not available, then receive the null and continues.</li></ol><p>When a process is blocking we call that synchronous, and when a process is not blocking we call asynchronous.</p><h4>Buffering</h4><p>Whether the communication is direct or indirect, messages reside in a temporary message queue. We call that buffer. Such queues can be implemented in three ways.</p><ol><li>Zero Capacity Buffer — In this queue maximum capacity is zero. Hence messages can’t wait in the queue until a process receives the message. So in this case, if the process wants to make sure that the receiver gets the message, the sender has to wait until the receiver gets the message.</li><li>Bound Capacity Buffer — This queue has a limited capacity of n. So n messages can wait in the queue until the receiving process retrieve the message. So the sender has not to wait until the receiver gets the message. But since the queue has limited capacity, if the queue is full then the sender has to wait or block until space available for the message in the queue.</li><li>Unbounded Capacity Buffer — There is no limit in the queue. So an infinite number of the message can wait in the queue. So the sender never has to wait.</li></ol><h4>Recap</h4><ul><li>Two types of processes in a computer system. Independent and co-operative.</li><li>The process needs to communicate with each other. We call that inter-process communication and processes using two operations as send() and receive() to communicate.</li><li>There are two main ways to communicate between processes. Those are shared memory and message passing.</li><li>Shared memory using a shared portion of memory and message passing doing via direct or indirect links.</li><li>In message passing, there are two varieties. Using direct links or Using Mail Box.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c97f5798ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/inter-process-communication-1c97f5798ea">Inter Process Communication</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in Elixir]]></title>
            <link>https://medium.com/runtimeerror/concurrency-in-elixir-bead3c09785e?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bead3c09785e</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[process]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 10:47:22 GMT</pubDate>
            <atom:updated>2020-04-16T23:02:14.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQOEdC9eef-qiJURjPw_vQ.jpeg" /></figure><p>If you have read my previous articles, you may know I am a kind of a parallel computing geek. So this is the reason. If you have pay for a PC 💻 and if that PC has two or more cores (Nowadays almost all the processor have more that one core), obviously you have to pay for those core even you are not consuming. In this case, I think you are a developer. Otherwise, it’s not up to you to decide whether you will consume all those cores 😛. So if you have pay for those, why don’t you consume it. Cores are expensive 💸.</p><p>Still confused 😕. Let me explain. First, let’s see how many cores do you have on your PC 💻. If you are in a windows machine just open the Task Manager and navigate to the Performance tab. You can easily find how many cores do you have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/0*FTwJVqE4W1sdeDNx.png" /></figure><p>If you are in Linux just type <strong>nproc </strong>you will get the number of core you have, or type <strong>lscpu </strong>and you can find more information about your processor. I had 4 cores on my laptop when I was writing this article. That means, if I consider this, I could have consumed my processor 4 times more than I’m consuming now.</p><p>Now I trust, as a developer, you have written millions of code lines in your laptop and have run. Now ask yourself, at least a single time did you consider consuming all those core with your awesome code. If the answer is <strong>no, </strong>don’t be upset. In the beginning, I event didn’t know there is such a thing called <strong>core</strong> rather than <strong>the processor</strong>.</p><p>The tragic story is this is the situation of many software companies. Just imagine, of all the developers out there (I mean careless developers like me 😜) consider about consuming all those core, how much energy they could have save for the world, just by not running several servers to do a task which they could have been done with less number of servers 😐. Per SE I said that it doesn’t mean that they did not need to consume their servers efficiently. There are many practical issues when writing code in a way that using all the cores. It is hard to write the synchronized code, which is using all the cores. <a href="https://hackernoon.com/why-concurrency-is-hard-a45295e96114"><strong>Read this article to learn much better, why it is a hard thing to write concurrent codes.</strong></a></p><p>This is where Elixir comes to the stage. Elixir is an awesome programming language that is run on Erlang VM (BEAM), which helps you to write software with concurrency. If you have studied concurrent programming before, you might have heard, <strong>process, thread, thread pool, locks, mutual exclusion, race conditions, deadlock, </strong>etc. and these words like the silence before the storm. But trust me, Elixir will save you. Keep in mind, this doesn’t mean, now it is a piece of cake to develop concurrent software with Elixir.</p><blockquote>Highly concurrent systems aren’t easy to write, but with Elixir, the language is on your side</blockquote><p>Now let’s see what’s happening to underline the Elixir to achieve concurrency. Elixir using the<strong> message passing</strong> method rather than shared<strong> memory</strong> and <strong>locks</strong> to communicate between processes (<a href="https://www.geeksforgeeks.org/inter-process-communication-ipc/"><strong>Read this article to learn more about inter-process communication</strong></a>). Elixir is using T<a href="https://en.wikipedia.org/wiki/Actor_model"><strong>he Actor Model</strong></a><strong> </strong>for this. An actor is a single-threaded process, which can make local decisions, create more actors, send more messages, and determine how to respond to the text message received.</p><p>Actor has these properties.</p><ul><li>Mail Box 📫</li><li>Process ID 🆔</li></ul><p>The mailbox is like the very mailbox in your house and the Process ID the same as the address of your house. Refer to this image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/0*BE51M8Uu3HgRhx5U.png" /><figcaption>Downloaded from <a href="https://rollout.io/blog/concurrency-in-elixir/">https://rollout.io/blog/concurrency-in-elixir/</a></figcaption></figure><h3>Implementation</h3><h4>Create a new process</h4><p>Now let’s see how to write concurrent code in Elixir with this actor model. Let’s create a sample function to learn this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6eca39f77f6b32c9b84c16d30106550/href">https://medium.com/media/f6eca39f77f6b32c9b84c16d30106550/href</a></iframe><p>We can use <strong>spawn/3 </strong>function to run this process asynchronously.</p><pre>iex&gt; pid = spawn(Example, :add, [3, 5])</pre><p>This will return the Process ID of the newly created process and write 8 to stdout. This newly created process is an Actor.</p><h4>Message Passing</h4><p>You already know inter-process communication makes concurrency much harder. Now let’s see how we can pass messages between processes in Elixir. In Elixir there are concepts for this: <strong>send/2</strong> and <strong>receive</strong>. We can send messages to processes by their Process ID and receive using <strong>pattern matching</strong> to receive messages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a984a81183b31a44ce876ea3ae7e330/href">https://medium.com/media/2a984a81183b31a44ce876ea3ae7e330/href</a></iframe><p>Now lets create a new process from this function and send some messages to that process.</p><pre>iex&gt; pid = spawn(Example, :messageReceiver, [])</pre><pre>iex&gt; send pid, {:ok, &quot;hello&quot;}<br>hello there<br>{:ok, &quot;hello&quot;} messageR</pre><pre>iex&gt; send pid, {:ok, &quot;who are you&quot;}<br>I am a Elixir Process<br>{:ok, &quot;who are you&quot;}</pre><pre>iex&gt; send pid, {:ok, &quot;how are you&quot;}<br>{:ok, &quot;how are you&quot;}</pre><p><strong>messageReceiver </strong>function catch <strong>{:ok, “hello”} </strong>and <strong>{:ok, “who are you”}</strong> messages and execute procedures bind to it.Here for <strong>{:ok, “hello”}</strong> message it writes “<strong>hello there</strong>” to stdout and for <strong>{:ok, “who are you”} </strong>message write “<strong>I am an Elixir process</strong>” to stdout. <strong>messageReceiver </strong>function not looking for a message like <strong>{:ok, “how are you”} </strong>and it just doesn’t care that message. You can see <strong>messageReceiver</strong> function working recursively not to stop after catching the first message.</p><h4>Process linking</h4><p>In Elixir we can use <strong>spawn_link </strong>to link a process to another process. So the parent process can notify if the child process crashed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1910abdda718dc7a85d921e76cc74bc/href">https://medium.com/media/e1910abdda718dc7a85d921e76cc74bc/href</a></iframe><pre>iex&gt; Example.run()<br>Process crashed: reason - crashed</pre><p>The<strong> run </strong>function creates a new process from <strong>iamgoingtocrash</strong> function and links that process to the parent process. When the child process crashed it parent can notify with <strong>{:EXIT, _from_pid, reason} </strong>type message.</p><p>These are the very basic concepts of implementing concurrency in Elixir. If you are interested to learn more read the following articles.</p><ul><li><a href="https://elixirschool.com/en/lessons/advanced/concurrency/">Concurrency in Elixir</a></li><li><a href="https://elixir-lang.org/getting-started/processes.html">Elixir Process</a></li></ul><p>Now you may wonder, where are those consuming all the cores thing happen. BEAM is responsible for that. BEAM is the Erlang virtual machine and our Elixir code will run on that VM. <a href="https://medium.com/flatiron-labs/elixir-and-the-beam-how-concurrency-really-works-3cc151cddd61"><strong>Read this article to understand how BEAM designed to use all the cores in your PC</strong></a><strong>.</strong></p><p>This is all that I’m going to discuss in this article. So if you want to become a parallel computing geek, you better add Elixir into your toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bead3c09785e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/concurrency-in-elixir-bead3c09785e">Concurrency in Elixir</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Switching in Depth]]></title>
            <link>https://medium.com/runtimeerror/context-switching-in-depth-1d6d4e51ab32?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6d4e51ab32</guid>
            <category><![CDATA[context-switching]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 06:12:45 GMT</pubDate>
            <atom:updated>2020-03-23T06:15:13.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rj1itGZkSXvCfiqKVo7TPQ.jpeg" /></figure><p>If you are a computer science student, then you must have heard the words <strong>Context switching</strong> before<strong>.</strong> In this article, we go deeper into context switching. If you are a computer science student, then you might also have a sound idea about operating systems. Context switching is a very important part of a modern operating system.</p><p>To understand context switching let’s use a metaphor. Imagine that you are a chef in a very busy restaurant in the city. Think about an evening where there are plenty of customers and orders. Since you are the chef you must work hard. Imagine you got an order for something like two eggs, vegetable soup and a burger (This may be the worst dish ever). Now, how are you going to finish these three dishes? Will you first boil the eggs, then cook the soup and then make the burger? Trust me. If I am the chef I won’t. I will cook all three dishes at the same time.</p><p>How do I do that? Well, first, I’ll put the eggs to boil and until that’s done, I will start making the soup and the burger at the same time. At one time I can do a little part of the soup and then do a little part of the burger. Finally, I can serve all 3 dishes.</p><p>Computer systems are no different from the above metaphor. The chef is the same as the processor. As you get many dishes to finish in a restaurant, the processor will get many tasks to do in a computer system. The restaurant chef has the experience to change between cooking soup and making a burger. In the computer system, there is a scheduler inside the operating system to switch the processor between those tasks. Now let’s see how this happens in a computer system from a computer science student’s viewpoint. The rest of the article is separated into a few subtopics to make this clear.</p><h4><strong>1. Application vs Process</strong></h4><p>All software developers write applications to manipulate hardware such as the processor and memory to achieve a goal like playing a video. But all the developers write software using some high-level language and the operating systems get the responsibility to manipulate hardware. When a developer creates such a code and makes an executable file from that, we call it an application. It is not something that is executing, but rather it is just a static entity that is in a hard disk or a flash drive. Once the application is launched it loads into the main memory and the processor starts to execute instruction by instruction.</p><p>So a process is an active entity. Once the application launches more than once, there are multiple processes from the same application, but these are at different run-times such as playing two films Star-wars and Avengers: Infinity war on two VLC players.</p><h4><strong>2. What a process looks like</strong></h4><p>When a process loads into the main memory it takes some amount of the memory and we call it an address space. Every process has its own virtual address space and it’s the job of the operating system to map that virtual address space with the physical address space. It’s nothing more than a simple map data structure that looks like this, <strong>{ virtual address: physical address }</strong></p><p>There are four main sections in this address space. Those are,</p><p>1. <strong>Text(Code)</strong> — The Text section is made up of the compiled program code, read in from non-volatile storage when the program is launched.</p><p>2. <strong>Data </strong>— The Data section is made up of the global and static variables, allocated and initialized before executing the main.</p><p>3. <strong>Heap </strong>— The Heap is used for the dynamic memory allocation, and is managed via calls to new, delete, malloc, free, etc.</p><p>4. <strong>Stack </strong>— The Stack is used for local variables. Space on the stack is reserved for local variables when they are declared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*_f2iSmSZjljF_VGi" /><figcaption>(Shared pages are used for inter-process communications purposes)</figcaption></figure><h4><strong>3.How a process is executed</strong></h4><p>What happens when a program that is being executed, is fed instruction by instruction to the processor and the processor starts to execute these instructions. If you are familiar with assembly language, then you could probably understand this quite easily. Refer to the following assembly code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*5tOdU8Beunnd4aL-.png" /><figcaption>Assembly Code</figcaption></figure><p>When a program is launched, the operating system feeds instructions into the processor line by line to execute and there is a register called program counter which responsible to save which line should be fed next. When executing those instructions, data in the process address space will be changed.</p><h4><strong>4.Multi-Processing</strong></h4><p>Imagine you are reading a book and you lost interest in it. Instead, now you want to read another book. What will you do? You will put a bookmark where you stopped reading and move on to the next book. This way, you can find where you stopped when you want to read that book again. The operating system is very much similar to this. If another process comes and if it has a higher priority than the process which is currently executing, the operating system must stop(there are few other states rather than stop and those will be discussed in a later section) the current process and start executing the next process. But the operating system should keep a snapshot of the old process to execute later. For that, the operating system has a Process control block — PCB. The process control block encloses all the details about the process. The PCB is created when the process is created. Some data of PCB changes when the state of the process changes. Some data changes frequently while the process is executing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/0*1OOCrI-Qho2Enc5E.jpg" /><figcaption>Process Control Block</figcaption></figure><p>Elements of a Process control block.</p><p>· <strong>Process state</strong> — State of the process (Running, Waiting, ready, terminated, etc.)</p><p>· <strong>Process-Id</strong> and the <strong>Parent process ID</strong></p><p>· CPU registers and Program Counter — <strong>Program Counter</strong> holds the address of the next instruction to be executed for that process.</p><p>· <strong>CPU Scheduling</strong> information — Such as priority information and pointers to scheduling queues.</p><p>· <strong>Memory Management information —</strong> For example, page tables or segment tables.</p><p>· <strong>Accounting information —</strong> The User and kernel CPU time consumed, account numbers, limits, etc.</p><p><strong>I/O Status information —</strong> Devices allocated, open file tables, etc</p><h4><strong>5.States of a process</strong></h4><p>Now we know that when a program is launched, it becomes a process. In a modern operating system, there are several states that the process can be in.</p><p>Once the process is executed in a processor, it is in the <strong>running</strong> state. Before it comes to the running state it has to wait in the <strong>ready</strong> state. Likewise, there are a few other states and those states have their own mechanisms to run a program efficiently. <strong>Context switching</strong> is changing the state of a process. Since it is not important to know what is happening in those states in detail right now, I am not going to explain them one by one. However, the following diagram will give you a clear idea about the states of a process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*WFtb1Awj8jjb-JwzCc_FoA.png" /><figcaption>States of a Process</figcaption></figure><h4><strong>6.Context Switching</strong></h4><p>As we discussed before context switching is the mechanism that is changing the state of the processes. Now, how does the operating system perform this task? As we discussed in the Multitasking section we know that the operating system uses a PCB (Process control block) to keep a snapshot of a process. Refer to the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*t06aZh4a2P3Xt-7KMUL6gw.png" /><figcaption>Context switching diagram</figcaption></figure><p>There are two processes as P0 and P1. Both processes have their own PCB. As I mentioned before a PCB is created when the process is created. At the start, the active PCB is that of P0. When P0 changes its state, thte operating system saves the current state in PCB0 and reloads PCB1. PCB1 contains a snapshot that was taken when P1 stopped previously, and when P1 changes its state, the operating system saves the current snapshot in PCB1 and reloads PCB0. It takes some time to reload and save PCB in memory. So, in that time both P0 and P1 processes have to wait in the idle mode.</p><p>So this is how the operating system achieves multi programming using context switching. If you are interested in learning further, I would suggest learning about Process Management in Operating Systems. This could help you learn how the scheduler decides which process to run as well as the various scheduler algorithms that are used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6d4e51ab32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/context-switching-in-depth-1d6d4e51ab32">Context Switching in Depth</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async in a nutshell : Hands on Asynchronous]]></title>
            <link>https://medium.com/runtimeerror/async-in-a-nutshell-hands-on-asynchronous-acf4d9e76454?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/acf4d9e76454</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Wed, 16 Oct 2019 16:46:04 GMT</pubDate>
            <atom:updated>2019-10-16T16:46:04.827Z</atom:updated>
            <content:encoded><![CDATA[<h3>Async in a nutshell : Hands on Asynchronous</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8L069N9dSp4h5umatzLFg.jpeg" /></figure><p>More responsiveness, more customers. More customers, more profit. Therefore, more responsiveness is more profit. In this article, I will discuss how to achieve more responsiveness in your applications with asynchronous programming using C# and asp.net framework. Before you start reading this article it may be better to read the previous articles of this <strong>async in a nutshell series</strong>. You can find them <a href="https://medium.com/@vmbckscc456/async-in-a-nutshell-getting-into-asynchronous-programming-24f738c7ff8d">here</a>.</p><p>There are two major benefits of asynchronous programming. The first benefit is, in client applications, you can enable responsiveness with asynchronous programming. Imagine you pick your phone up and go to your favorite app. Then you press a button which make a request over the internet for some data and the UI gets blocked until the response is received. This decreases the user experience and you will be potentially losing customers. You can get rid of this blocking behavior using asynchronous programming.</p><p>The second major benefit belongs to the server-side. Imagine you develop a server that can’t respond to a request until it finishes a database call made by another request. It’s a nightmare for any kind of business which relies on their servers. You can improve the efficiency of your servers with asynchronous programming so that they can handle a request while the database call gets finished which made by another request.</p><p>As I mentioned in the previous article it is not an easy thing to write asynchronous code. But latest frameworks have made it almost as easy as writing normal synchronous code. In this series I’m using C# and asp.net framework to explain how to write asynchronous code.</p><p>When you are going to write asynchronous code in C# you have to consider 4 main things. (There are plenty of things to consider, but for better understanding I have summarized those into 4 major points.)</p><ol><li><strong>async </strong>operator</li><li><strong>await </strong>operator</li><li><strong>Task</strong> return type</li><li>Method name</li></ol><p>Here I have included a brief discussion on preceding points. If you are new to asynchronous programming in C#, then you most probably will not get what I have said straightaway. So, please make sure to read calmly and move into next article where I have explained those points with real-life examples.</p><h4><strong>async operator</strong></h4><p>There are two main intentions of the <strong>async</strong> operator. The first one is async operator enables await operator to be used inside a method. The second one is async operator converts an asynchronous method into a <a href="https://www.freecodecamp.org/news/state-machines-basics-of-computer-science-d42855debc66/"><strong>state machine</strong></a> which I’m not going to discuss in-depth in this article. Just for your information, state machine is something like a switch which can set its state with respect to some value. Imagine the switch operator in C# or any other language you prefer. A state machine is also something like that. Let us talk about the state machine in another article later.</p><h4><strong>await operator</strong></h4><p>Similar to the <strong>async </strong>operator, the await operator has two major purposes. The first one is, the <strong>await </strong>operator<strong> </strong>tells the compiler that the method including the <strong>await</strong> operator can’t continue without completing the asynchronous task. The second is that the <strong>await</strong> operator returns the control to the caller.</p><h4><strong>Task return type</strong></h4><p>In contrast to synchronous methods, here we don’t return a simple data type like Integer, String, Boolean or an instance of some class. Here we are returning a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=netframework-4.8"><strong>Task</strong></a> or <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1?view=netframework-4.8"><strong>Task&lt;T&gt;</strong></a> where T is Integer, string, Boolean or any other class. The task is something like a promise. (Don’t mess this up with JS promises you already know) A promise which says hey, ‘Some time later I will return a result with either nothing or some other data type’. If we are not returning anything inside of our asynchronous method then we can simply use <strong>Task</strong> as the return type. If we are going to return something then we can use Generic type tasks <strong>Task&lt;T&gt; </strong>where T is the data type that we are going to return. Remember we can’t return a void inside of an asynchronous method unless it is an event handler. If it is an event handler then we can simply return void.</p><h4><strong>Method signature</strong></h4><p>This one is not compulsory when you are writing an asynchronous method. But this is the best practice you can use in order to write a clean code. (<a href="https://medium.com/@hasangalakdinu/writing-clean-code-b97e2bd5e6bd">This is a really good article that you can read about the importance of writing clean code</a>). When we are writing an asynchronous method we append <strong>Async </strong>to the end of the method name. As an example asynchronous version of <strong>DownloadWebPage() </strong>is <strong>DownloadWebPageAsync().</strong></p><p>If you have any hands-on experience in C# you might get what I have explained above. Even though you have not much experience, you will be able to get a much better understanding on asynchronous programming after reading the next article of this <strong>async in a nutshell series</strong>. There I will explain these points using a simple <a href="https://docs.microsoft.com/en-us/dotnet/framework/wpf/getting-started/"><strong>WPF </strong></a>application that is download and shows a website using a web request.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acf4d9e76454" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/async-in-a-nutshell-hands-on-asynchronous-acf4d9e76454">Async in a nutshell : Hands on Asynchronous</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async in a nutshell : Why developers should write processor killing codes]]></title>
            <link>https://medium.com/runtimeerror/async-in-a-nutshell-why-developers-should-write-processor-killing-codes-f3dae6af8819?source=rss-9d5093d9fab1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3dae6af8819</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Buddhika Chathuranga]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 17:46:04 GMT</pubDate>
            <atom:updated>2019-10-11T03:53:21.482Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Async in a nutshell : Why developers should write processor killing codes</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bwr5ssiykSpW-clWbuHpag.jpeg" /></figure><p>These days most of the companies don’t have their own processing power. They hire processing power through infrastructure services like Amazon. So developers have a huge responsibility in order to write processor killing codes (I’ll explain that later). That is why asynchronous programming has become a trending topic in the tech world. If you are really new to asynchronous programming it is better to read the first article of this <strong>async in a nutshell</strong> series, <a href="https://medium.com/@vmbckscc456/async-in-a-nutshell-getting-into-asynchronous-programming-24f738c7ff8d"><strong>Get into async</strong></a> before you start reading this. In this article we are going to discuss synchronous, asynchronous and multi-threading with respect computers using some rather silly examples just to make it easier for everyone.</p><p>First lets us understand why we needed asynchronous programming. To understand this, it is important to be aware of <strong>processor bound operations</strong> and <strong>I/O bound operations</strong>. In a computer system there are few types of operators such as processor bound operations, I/O bound operations, memory-bound operations so on. But here we care only about processor bound operations and I/O bound operations. Processor bound operations are the operations that depend on the processor such as doing an arithmetic calculation. I/O bound operations are the operations that do not directly depend on the processor but on the I/O peripherals such as fetching data from a database through an HTTP request or write or read data from a file which is located in the hard disk.</p><blockquote>If simply explained, we say that a program is a processor bound program if the program runs faster if the CPU were faster and a program is I/O bound program if the network subsystem was faster. Refer to the image below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*O0HjKq-YRSPlvorOqEfJrQ.png" /></figure><p>Imagine the function named <strong>GetDataOnline()</strong> is a function that fetches data from an API endpoint through an HTTP request. Imagine that request takes about 3 seconds to fetch data from the internet. So the code lines below that function call will have to wait until that request to finish or time out before executing. That doesn’t seem like a big problem. But imagine this is the UI thread of the program and when the program is blocked we can’t control the UI. This means we can’t minimize, move or even close the program until the <strong>GetDataOnline()</strong> function is finished. That is a very bad user experience. This becomes the worst when it comes to something like a web server. Imagine the server has to wait until it finishes some database queries to handle another request. That’s totally enough to destroy the whole business.</p><p>So there are few workarounds to tackle this problem. One approach is <strong>multi-threading</strong>. Nowadays almost all the computer systems have multi-cores. The core is a single processing unit that can do a task. When there are multi-cores it is possible to do many tasks at once. Even though there is a single core it is still possible to do several tasks at once. But what actually happens there, is time-slicing between the tasks (threads). However when there are multi-cores in a computer system then we can hand over the responsibility of different tasks (threads) to different cores. Then those cores can work in isolation. But the problem starts when those threads start to work with common resources like memory. When those threads interact with common resources its really difficult to manage the synchronization between the threads and it becomes really hard to communicate between those threads. This is why <strong>asynchronous programming</strong> is important.</p><p>The asynchronous program does not consume extra threads to do these I/O bound operations. Instead, Asynchronous programming uses futures and callbacks. Actually the processor should not need to wait until I/O operations are finished. Look at the image given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*A_aDU8SFBEkH816_uoqG5Q.png" /></figure><p>Imagine <strong>GetDataFomFile() </strong>is a function that fetches data from a file in the hard disk. Imagine it takes about 3 seconds to finish this task. Now again the code below the <strong>GetDataFromFile() </strong>has to wait until this task finished. But in asynchronous programming it doesn’t happen in this way. In asynchronous programming the OS just hands over that process to the device driver which executing the I/O operation and continues with the code below the <strong>GetDataFromFile(). </strong>It does so by first constructing an object that represents the read request. This is called an <strong>I/O request packet (IRP)</strong>.</p><p>The device driver receives the IRP and issues a command to the device to write out the data. If the device supports Direct Memory Access (DMA), this can be as simple as writing the buffer address to a device register. That’s all the device driver can do; it marks the IRP as “pending” and returns to the OS.</p><p>See, it did not create an extra thread or wait until <strong>GetDataFromFile() </strong>finished. When the task eventually finishes, the program can continue with it. There may be some service threads in order to handle this callback. But still this is better than synchronize executing or multi-threading, isn’t it? Since we are not waiting for the processor until I/O operations happen we can utilize the processor as much as we pay. We can kill the processor.</p><p>There is a great article on asynchronous programming <a href="https://blog.stephencleary.com/2013/11/there-is-no-thread.html"><strong>There is no thread</strong></a><strong> </strong>which you can refer.</p><p>In general it is not really easy to write asynchronous code, but latest frameworks have made it much easier and provide a lot of support. So, in next article let us see how to write an asynchronous program using C# and asp.net framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3dae6af8819" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtimeerror/async-in-a-nutshell-why-developers-should-write-processor-killing-codes-f3dae6af8819">Async in a nutshell : Why developers should write processor killing codes</a> was originally published in <a href="https://medium.com/runtimeerror">RuntimeError</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>