<?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 Sławek on Medium]]></title>
        <description><![CDATA[Stories by Sławek on Medium]]></description>
        <link>https://medium.com/@slawek.pl?source=rss-4dd4c282f0b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hWpXJSByR4mn-klm0sdsiA.jpeg</url>
            <title>Stories by Sławek on Medium</title>
            <link>https://medium.com/@slawek.pl?source=rss-4dd4c282f0b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:22:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@slawek.pl/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[Improve the Performance of Your Python Code: Lists vs Generators]]></title>
            <link>https://medium.com/@slawek.pl/improve-the-performance-of-your-python-code-lists-vs-generators-56f08d9c5e7d?source=rss-4dd4c282f0b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/56f08d9c5e7d</guid>
            <category><![CDATA[python-performance]]></category>
            <category><![CDATA[python-list-comprehension]]></category>
            <category><![CDATA[python-list]]></category>
            <category><![CDATA[python-generators]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sławek]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 15:32:32 GMT</pubDate>
            <atom:updated>2023-09-18T15:32:32.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*fMd6kbeWooUA3j1OSzYCNA.png" /></figure><p>Python is a powerful, interpreted programming language that has gained popularity for its simplicity and elegance. Created in the 1980s by Guido van Rossum, Python has since become one of the most popular programming languages in the world. It’s known for its highly readable code and syntax that encourages writing programs that are both simple and efficient.</p><p>Part of this simplicity is Python’s wide range of built-in features that make it versatile. Two of these features, lists and generators, are essential for many Python applications, ranging from simple scripts to complex data processing systems.</p><p>Lists are a basic data type in Python used for storing collections of items. They are incredibly flexible, allowing you to store various types of data and manipulate them in different ways.</p><p>On the other hand, generators are a more advanced data structure that allows you to generate values “on the fly.” This is crucial in many situations, especially when dealing with large amounts of data that are too big to store in memory all at once.</p><blockquote>In this article, we’ll dive into these two key Python elements, comparing them and discussing their various applications. Whether you’re a Python beginner or an experienced specialist, understanding the differences and similarities between lists and generators is key to effectively using the language.</blockquote><h3>Definition and Description of Lists in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*89cpdomG5BLaidyvjc-WAw.png" /></figure><p>In Python, a list is a data structure that can hold multiple elements. These elements can be of any type, such as integers, floating-point numbers, strings, and even other lists or objects. A list is one of the four built-in data types in Python used for storing collections of data; the other three are tuple, dictionary, and set.</p><p>A list in Python is an ordered collection, which means that the elements maintain their order. This order is determined by an index that represents the position of the element in the list. Indexing in Python starts from zero, meaning that the first element in the list has an index of 0, the second has an index of 1, and so on.</p><p>Lists are defined by placing the elements in square brackets [][], separated by commas. Here’s an example of a list:</p><pre>my_list = [1, 2, &quot;three&quot;, 4.0, [5,6]]</pre><p>In this example, <em>my</em>_<em>list</em> contains five elements: two integers, a string, a floating-point number, and another list. This demonstrates how lists can store various types of data.</p><p>Lists in Python are <em>mutable</em> which means their content can be modified after they are created. You can add, remove, and change elements in the list.</p><blockquote>Overall, lists are extremely versatile and useful in many different situations, ranging from simple to very complex applications. They are one of the most commonly used data types in Python.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*afe9rafC8dNu6ln0AnNsAw.png" /></figure><h3>How to Create and Manipulate Lists</h3><h4>Creating Lists</h4><p>Lists in Python are created by placing values separated by commas inside square brackets []. These values can be of any type: numbers, strings, and even other lists. For example:</p><pre>number_list = [1, 2, 3, 4, 5]<br>string_list = [&quot;one&quot;, &quot;two&quot;, &quot;three&quot;]<br>mixed_list = [1, &quot;two&quot;, 3.0, [4, 5]]</pre><p>You can also create an empty list using empty square brackets [] or by using the list() function.</p><h4>Adding Elements to Lists</h4><p>There are multiple ways to add elements to a list. The simplest way is to use the append() method, which adds an element at the end of the list:</p><pre>number_list.append(4)</pre><p>Another way is to use the insert() method, which adds an element at a specific index:</p><pre>number_list.insert(1, 2)</pre><h4>Removing Elements from Lists</h4><p>You can remove elements from a list in several ways. You can use the remove() method, which removes the first occurrence of a specific value:</p><pre>number_list.remove(2)</pre><p>You can also use the pop() method, which removes an element at a specific index and returns it:</p><pre>deleted_item = number_list.pop(2)</pre><h4>Modifying Elements in Lists</h4><p>Lists in Python are mutable, meaning you can modify their elements after creation. You can do this by referring to the list element by its index:</p><pre>number_list[1] = 200</pre><h4>List Comprehensions in Python</h4><p>List comprehensions are one of the most powerful tools in Python, allowing you to create new lists in a single, concise line of code. They allow you to transform one list (or any other iterable object) into another list by applying an expression to each element of the source list.</p><p>The syntax for list comprehensions is:</p><pre>new_list = [expression for element in old_list if condition]</pre><p>Here’s an example that creates a list of squares of numbers from 0 to 9:</p><pre>squares = [x ** 2 for x in range(10)]</pre><p>You can also add conditions to list comprehensions. For instance, you can create a list of squares of even numbers from 0 to 9:</p><pre>squares = [x ** 2 for x in range(10) if x % 2 == 0]</pre><blockquote>List comprehensions are a very efficient and readable way to create and transform lists in Python. Due to their conciseness and clarity, they are often used in practical coding.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*dvGg3sNjQzHNtEc75QM3fA.png" /></figure><h3>Definition and Description of Generators in Python</h3><p>A generator in Python is a special type of iterator that implements the __next__() method. Unlike lists, which store all their content in memory, generators generate values &quot;on the fly,&quot; meaning they produce one value at a time when needed.</p><p>Generators are most commonly used when working with large datasets that are too big to fit into memory at once, or when the data generation process is resource-intensive and you want to defer it until necessary.</p><h4>Creating Generators</h4><p>Generators are created using functions, but instead of using the return keyword to return values, you use yield. When a generator function is called, it returns a special generator object. When the __next__() method of this object is called (usually via the built-in next() function), the function&#39;s code runs until it hits yield, and the value following yield is returned. Here&#39;s an example of a simple generator:</p><pre>def simple_generator():<br>    yield 1<br>    yield 2<br>    yield 3<br>gen = simple_generator()<br>print(next(gen))  # Output: 1<br>print(next(gen))  # Output: 2<br>print(next(gen))  # Output: 3</pre><p>In this example, simple_generator is a function that returns a generator. Each time next(gen) is called, the function&#39;s code runs until it encounters yield, and then the value after yield is returned.</p><h4>Using Generators</h4><p>You can iterate through a generator just like a list using a for loop:</p><pre>for number in gen:<br>    print(number)</pre><p>Or you can call the next() function on the generator to get the next value:</p><pre>print(next(gen))  # Output: 1<br>print(next(gen))  # Output: 2<br>print(next(gen))  # Output: 3</pre><p>It’s important to note that once all values have been generated, the generator becomes empty. Trying to call next() on an exhausted generator will result in a StopIteration exception.</p><h4>Generator Comprehensions</h4><p>Python also offers generator comprehensions, which are similar to list comprehensions, but instead of using square brackets [][], you use parentheses ().</p><pre>gen = (x ** 2 for x in range(10))<br>for number in gen:<br>    print(number)</pre><blockquote>Generators in Python are a powerful tool for creating sequences of values in a memory-efficient manner. Thanks to their “lazy” nature, they are particularly useful when working with large datasets or when generating each value is resource-intensive.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*VE2wYPmlSmkmgc5E0nsArg.png" /></figure><h3>Overview of Differences and Similarities Between Lists and Generators</h3><p>Lists and generators in Python are both sequential objects, meaning you can iterate through them in a specific order. Although they share many similarities, there are key differences that dictate when to use each.</p><h4>Similarities</h4><ul><li>Iterability: Both lists and generators are iterable, meaning you can loop through their elements using a for loop.</li><li>Comprehensions: You can use comprehensions to create new list or generator objects in a more concise and readable way.</li></ul><h4>Differences</h4><ul><li>Memory: Lists store all their elements in memory at once, while generators generate values “on the fly” and do not store them. This means generators are more memory-efficient, especially when dealing with large data sets.</li><li>Laziness: Generators are “lazy,” meaning they generate values only when needed. This allows you to defer costly calculations until the values are actually required.</li><li>Single-use: Generators can be iterated through only once. After all values have been generated, the generator becomes empty. In contrast, you can traverse lists as many times as needed.</li><li>Mutability: Lists are mutable, allowing you to change, add, or remove elements. Generators, on the other hand, are immutable — once created, they cannot be changed.</li></ul><h4>Conclusion</h4><blockquote>Both lists and generators have their place in Python. Lists are ideal for storing small to medium-sized data sets that are frequently modified, while generators are better suited for handling large data sets or calculations that are resource-intensive and should be deferred.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56f08d9c5e7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Key Element in the Work of a Software Engineer]]></title>
            <link>https://medium.com/@slawek.pl/a-key-element-in-the-work-of-a-software-engineer-b01f6865507e?source=rss-4dd4c282f0b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b01f6865507e</guid>
            <dc:creator><![CDATA[Sławek]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 19:19:49 GMT</pubDate>
            <atom:updated>2023-08-17T19:19:49.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*nLhQ_wvN7fjyRfEvLkx9wQ.png" /></figure><h3>Introduction</h3><p>Have you ever wondered what separates an average Software Engineer from an outstanding one? Perhaps you think it’s about perfectly written code, covered with thorough unit and integration tests, error-free, and meeting the strictest performance criteria. Indeed, this is important, but it’s irrelevant if you lack the ability to share knowledge with your team. Herein lies a key element often overlooked in the work of a Software Engineer: code comments.</p><h3>Why Are Code Comments So Important?</h3><p>There’s a widespread, misguided belief that creating comments in code is an unnecessary waste of time. In reality, even the most understandable code can cause difficulties for new programmers or those who haven’t worked on a particular part of the project for a long time.</p><p>Understanding code takes more time than reading a few lines of annotations that describe the functionality of a function, method, or class. Our ability to remember is limited, and comments can prove to be an invaluable supporting tool.</p><h3>My Experience and Habit of Creating Code Comments</h3><p>With over a decade of programming experience, I have developed the habit of adding comments to every significant part of the code.</p><p>To illustrate the importance of this practice, let’s consider two examples of code. The first example is devoid of comments and uses vague variable names, while the second is well-documented.</p><h4>Example 1: Code Without Comments</h4><pre>def p(x=52, y=13, z=4):<br>    if x != 52 or y != 13 or z != 4:<br>        raise ValueError()<br>    return 1 / x</pre><p>In this example, the lack of comments and the use of vague variable names make it more difficult to understand the code’s purpose and functionality. A newcomer to the code or someone unfamiliar with the context might struggle to understand what the code is intended to achieve.</p><h4>Example 2: Well-Documented Code</h4><pre>def probability_of_ace_of_hearts(deck_size=52, number_of_hearts=13, number_of_aces=4):<br>    &quot;&quot;&quot;<br>    Calculates the probability of drawing the Ace of Hearts from a standard deck of cards.<br><br>    This function assumes a standard deck size of 52 cards, with 13 hearts and 4 aces.<br>    The probability is calculated based on the assumption that there is only one Ace of Hearts in the deck.<br><br>    :param deck_size: int, total number of cards in the deck, default is 52.<br>    :param number_of_hearts: int, total number of hearts in the deck, default is 13.<br>    :param number_of_aces: int, total number of aces in the deck, default is 4.<br>    :return: float, probability of drawing the Ace of Hearts, expressed as a fraction of 1.<br>    <br>    Related Jira task: JIRA-1234<br>    &quot;&quot;&quot;<br><br>    if deck_size != 52 or number_of_hearts != 13 or number_of_aces != 4:<br>        raise ValueError(&quot;Parameters do not match the standard deck configuration.&quot;)<br>    probability = 1 / deck_size<br>    return probability</pre><p>These examples help to reinforce the thesis that comments in code are vital for maintaining readability and understanding, especially for team members who may not be familiar with the specific code or its context.</p><h3>Conclusion</h3><p>Code comments are not just an addition; they are a key element in the work of every software engineer. The time spent creating clear and precise annotations is an investment that pays off in the future. Do not neglect this aspect, as it may be the difference between being average and an exceptional specialist in your field.</p><p>I hope this article has been helpful. If you have any questions, please feel free to ask in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b01f6865507e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Simultaneity: Asynchrony and Multithreading in Python]]></title>
            <link>https://medium.com/@slawek.pl/the-art-of-simultaneity-asynchrony-and-multithreading-in-python-1c87bcfc0bd?source=rss-4dd4c282f0b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c87bcfc0bd</guid>
            <dc:creator><![CDATA[Sławek]]></dc:creator>
            <pubDate>Fri, 26 May 2023 08:09:47 GMT</pubDate>
            <atom:updated>2023-05-30T07:51:26.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaBLWMmTOd2zSqiNCZxxyQ.png" /></figure><h3>Entry</h3><p>Consider the activities we do every day: if we want to do several things at once, we don’t wait for one to finish before starting the next. Instead, we do them simultaneously, saving time.\</p><p>The same is true of computers. Many strategies have been devised to allow computers to do many things simultaneously, such as asynchronous programming and multithreading.</p><p>— — — — — — — —</p><p><em>Today, we’ll explore these two concepts in the context of Python.</em></p><h3>First Chapter: Introduction to Asynchronous and Multithreaded Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_L7OHISL14eV9VMhaJ1gVQ.png" /></figure><p>— — — — — — — —</p><p><em>In the first part of this article, we will discuss what asynchronous and multi-threaded programming is, what their advantages are, and the basic differences between them. We’ll see how these techniques help computers make better use of their resources and increase performance.</em></p><h4>What is asynchronous programming?</h4><p>Asynchronous programming is a style of programming that allows operations to be performed independently of the main program thread.</p><blockquote>This means you don’t have to wait for one operation to finish before starting another.</blockquote><p>Thanks to this, resources are used more efficiently, which is especially important for I/O operations, such as reading and writing to files, network requests, interactions with databases, where delays are unavoidable.</p><h4><strong>What is Multi-threaded Programming?</strong></h4><p>Multi-threaded programming is an approach that allows multiple tasks (threads) to be executed simultaneously within a single process.</p><blockquote>Threads share process memory, which means they can share data easily, but on the other hand, thread synchronisation is a key element to avoid conflicts when accessing resources.</blockquote><h4>Differences Between Asynchronous and Multi-threaded Programming</h4><p>The primary difference between asynchronous and multi-threaded programming is how tasks are managed.</p><p>In asynchronous programming, everything is done in a single thread, but tasks are interrupted and resumed at the appropriate times.</p><p>On the other hand, multi-threaded programming consists in running tasks simultaneously in different threads.</p><p>An important difference is also how both approaches deal with blocking operations.</p><p>In asynchronous programming, blocking operations are broken to allow other tasks to be performed.</p><p>In multi-threaded programming, blocking operations are performed in separate threads, allowing other threads to continue working.</p><h4>Advantages and Disadvantages of Asynchronous Programming</h4><p>Asynchronous programming is especially effective for I/O operations such as file, network, and database operations, where waiting for operations to complete is the norm.</p><p>The advantage of asynchronous programming is that it does not require large system resources such as threads, which makes it more scalable for large numbers of tasks.</p><p>However, asynchronous programming can be more difficult to understand and debug due to the unusual control flow.</p><blockquote>In addition, it is limited to a single CPU core, which means it is unable to take advantage of CPU multi-cores.</blockquote><h4>Advantages and Disadvantages of Multithreaded Programming</h4><p>Multithreaded programming feels more natural to the human mind because the control flow in a multithreaded program is more linear.</p><blockquote>In addition, multi-threaded programs can take advantage of multi-core processors, which allows for increased performance by simultaneously executing tasks.</blockquote><p>On the other hand, multi-threaded programming is associated with a greater overhead on system resources.</p><p>Each thread requires additional memory and operating system resources. In addition, it requires the use of synchronization techniques such as locks and semaphores to avoid race conditions, which can lead to additional complexity.</p><h4>Choosing Between Asynchronous and Multi-threaded Programming</h4><p>The choice between asynchronous and multi-threaded programming depends on the specifics of the task.</p><p>If I/O is a major part of the task, asynchronous programming may be a good choice because of its efficiency in such operations.</p><p>If the task consists mainly of computations that can be performed on multiple CPU cores in parallel, multi-threaded programming may be a better choice.</p><p>In practice, many applications use both asynchronous and multi-threaded programming, depending on the requirements of the specific tasks.</p><blockquote>Python with its asyncio and threading libraries offer good support for both approaches, allowing flexibility in choosing a task management strategy.</blockquote><p>— — — — — — — —</p><p><em>In the following chapters, we’ll take a closer look at how these techniques are applied in Python, both in theory and in practice.</em></p><h3>Second Chapter: Python Asynchronous Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjWKzsr5h3R1bn2uRMA4sg.png" /></figure><p>— — — — — — — —</p><p><em>In this part we will focus on asynchronous programming in Python. We’ll take a look at the asyncio library, which is a built-in library for asynchronous programming in Python. Code examples will help you understand what practical use of asynchronous code looks like.</em></p><h4>Introduction to Asyncio</h4><p>Asyncio, available since Python 3.5, is a built-in Python library that supports asynchronous programming.</p><p>In particular, asyncio provides tools to handle I/O operations without thread blocking, leading to greater scalability and application performance.</p><h4>Async and Await Syntax</h4><p>To understand asyncio, it is crucial to understand two keywords: async and await. Asynchronous functions in Python are defined with the async def keyword.</p><pre>async def hello():<br>    print(&quot;Hello,&quot;)<br>    await asyncio.sleep(1)<br>    print(&quot;World!&quot;)</pre><p>The hello function above is asynchronous. When we use await before `asyncio.sleep(1)`, it means that the function will suspend for a second before it prints “World!”.</p><h4>Event Loop</h4><p>The basic concept of asyncio is the event loop. This is an infinite loop that handles asynchronous events.</p><p>These events may include I/O operations, timeouts, and other operations that do not block program execution.</p><p>We start the event loop as follows:</p><pre>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(hello())</pre><p>`asyncio.run` starts an event loop and then calls hello. After the hello call is complete, the event loop closes.</p><h4>Asyncio.create_task()</h4><p>The `asyncio.create_task()` method is an extremely useful tool in asynchronous Python programming. It allows you to create tasks from coroutines that are immediately scheduled to run.</p><blockquote>This means that they are ready to run as soon as the event loop can handle them.</blockquote><p>The key element of asyncio is that while tasks run “in parallel”, everything happens within a single thread. This is possible thanks to the mechanism of returning control to the event loop when the task is unable to proceed without waiting for some event (for example, completion of an I/O operation).</p><p>The fact that everything happens within a single thread has several important consequences. First, there is no need for locks or other synchronization mechanisms that are necessary for true multi-threaded programming.</p><p>Second, asynchronous programming is very efficient at handling I/O, which is often a major constraint in large network applications.<br>Consider the following example:</p><pre>async def task1():<br>    print(&quot;Task 1 start&quot;)<br>    await asyncio.sleep(1)<br>    print(&quot;Task 1 end&quot;)<br><br>async def task2():<br>    print(&quot;Task 2 start&quot;)<br>    await asyncio.sleep(1)<br>    print(&quot;Task 2 end&quot;)<br><br>async def main():<br>    t1 = asyncio.create_task(task1())<br>    t2 = asyncio.create_task(task2())<br>    <br>    await t1<br>    await t2<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>When you run this code, you will see that task1 and `task2` start executing one after the other but finish at the same time.</p><p>This is because when `task1` is suspended (waiting for `asyncio.sleep(1)`), the event loop goes to `task2`.</p><p>When `task2` is also suspended, the event loop returns to task1 (if it has already finished waiting), then to task2, and so on until both tasks are finished.</p><p>Thus, although tasks are executed on a single thread, the asynchronous nature of the operations allows them to be “parallel” executed.</p><p>This shows the power of asyncio and asynchronous Python programming.</p><h4>Practical Applications of Asyncio</h4><p>The asyncio library is extremely useful for many asynchronous applications.</p><p>Thanks to it, it is possible to create asynchronous web applications, support multiple network connections, and support time-based tasks.</p><p>In this section, we will discuss one practical example of using asyncio, which is asynchronous retrieval of data from multiple sources.</p><p>Let’s assume that we are dealing with a situation where we need to retrieve data from various APIs. In many cases, operations like this can take a long time due to network latency or server speed limitations.</p><blockquote>Thanks to asyncio, we can perform these operations asynchronously, which significantly speeds up the whole process.</blockquote><p>Here is a sample code that illustrates how this can be done:</p><pre>import aiohttp<br>import asyncio<br><br>async def fetch_page(session, url):<br>    async with session.get(url) as response:<br>        return await response.text()<br><br>async def main():<br>    urls = [<br>        &quot;http://www.python.org/&quot;,<br>        &quot;http://docs.python.org/3/&quot;,<br>        &quot;http://www.python.org/success-stories/python-for-collaborative-robots/&quot;<br>    ]<br>    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:<br>       tasks = [asyncio.create_task(fetch_page(session, url)) for url in urls]<br>       pages = await asyncio.gather(*tasks)<br><br>    page1_content, page2_content, page3_content = pages<br>    print(page1_content, page2_content, page3_content)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>In the code above, we first create a list of URLs from which we want to fetch data. Then, using the `asyncio.create_task()` method, we create tasks that asynchronously fetch data from each URL.</p><p>The `asyncio.gather()` method is used to wait for all tasks to complete and collect the results into a list.</p><p>Finally, we have access to the data returned by all three APIs, which we can use later in our program.</p><blockquote>This way of asynchronously fetching data is much more efficient than calling each of the APIs sequentially.</blockquote><p>Thanks to asyncio, I/O operations that would normally block our program from running are performed in parallel, which allows us to significantly speed up the execution of the task.</p><h3>Third Chapter: Multi-threaded Programming in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMuJMM-ToA3gIbH93gRYxg.png" /></figure><p>— — — — — — — —</p><p><em>Multi-threaded programming is one of the fundamental aspects of creating high-performance applications. It gives the possibility of simultaneous execution of different parts of the code, which in many cases can significantly increase the speed of the program. In Python, the threading module is a tool for creating multi-threaded applications.</em></p><h4>What is a Thread?</h4><p>A thread, also known as a lightweight process, is the smallest computational unit that the operating system can schedule for execution.</p><p>Threads within a single process share memory and resources so that they can effectively communicate and collaborate with each other.</p><p>In Python, each thread is represented by a Thread object from the threading module.</p><h4>Creating Threads in Python</h4><p>Let’s see a more elaborate example that demonstrates creating multiple threads.</p><blockquote>In this example, we will create five threads, each of them will execute a worker function that simulates a time-consuming operation.</blockquote><pre>import threading<br>import time<br><br>class Worker:<br>    def __init__(self, number):<br>        self.number = number<br>        self.thread = threading.Thread(target=self.run)<br><br>    def run(self):<br>        print(f&quot;Thread {self.number} is starting&quot;)<br>        time.sleep(2)  # simulation of time-consuming operation<br>        print(f&quot;Thread {self.number} exits&quot;)<br><br>class WorkersGroup:<br>    def __init__(self, count):<br>        self.workers = [Worker(i) for i in range(count)]<br><br>    def start_all(self):<br>        for worker in self.workers:<br>            worker.thread.start()<br><br>    def join_all(self):<br>        for worker in self.workers:<br>            worker.thread.join()<br><br>if __name__ == &quot;__main__&quot;:<br>    workers_group = WorkersGroup(5)<br>    workers_group.start_all()<br>    workers_group.join_all()</pre><p>When we run this code, we’ll see that the threads are executing concurrently, not one after the other.</p><h4>Thread Synchronization</h4><p>Now let’s see how to use Lock to synchronize threads.</p><p>Suppose we have a resource (like a file or data structure) that can be modified by different threads, and we want to ensure that only one thread at a time can modify it.</p><pre>import threading<br>import time<br><br>class SharedResource:<br>    def __init__(self):<br>        self.data = []<br><br>    def worker(self, number, lock):<br>        print(f&quot;Thread {number} wants to modify resource&quot;)<br>        with lock:<br>            print(f&quot;Thread {number} modifies resource&quot;)<br>            self.data.append(number)<br>            time.sleep(2)  # simulate a time-consuming operation<br>        print(f&quot;Thread {number} has finished modifying the resource&quot;)<br><br>    def run(self):<br>        lock = threading.Lock()<br>        threads = []<br>        for i in range(5):<br>            thread = threading.Thread(target=self.worker, args=(i, lock))<br>            threads.append(thread)<br>            thread.start()<br><br>        # We are waiting for all threads to finish<br>        for thread in threads:<br>            thread.join()<br><br>        print(f&quot;Shared resource after thread modification: {self.data}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    shared_resource = SharedResource()<br>    shared_resource.run()</pre><p>In this example, each thread tries to add its number to the data list. Without a lock, threads could try to modify the list concurrently, which could lead to unexpected results.</p><blockquote>Thanks to the lock, each thread has to wait its turn.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c87bcfc0bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>