<?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 Luca Bonamini on Medium]]></title>
        <description><![CDATA[Stories by Luca Bonamini on Medium]]></description>
        <link>https://medium.com/@lucabonamini?source=rss-a63a387df30e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*clszFgtIXkpy6C4npCaQ6Q.jpeg</url>
            <title>Stories by Luca Bonamini on Medium</title>
            <link>https://medium.com/@lucabonamini?source=rss-a63a387df30e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:42:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucabonamini/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[Creating reusable libraries with CMake & C++: a Step-by-Step guide]]></title>
            <link>https://levelup.gitconnected.com/creating-reusable-libraries-with-cmake-c-a-step-by-step-guide-aa9f1180301?source=rss-a63a387df30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9f1180301</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[cmake]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Luca Bonamini]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 17:58:03 GMT</pubDate>
            <atom:updated>2024-02-25T16:51:21.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hC0Nfain_Iu_snsRaXGkcQ.jpeg" /></figure><h3>Introduction</h3><p>Have you ever wondered how to create reusable libraries with CMake, the powerful cross-platform build system? If so, you are not alone. Many developers face the challenge of writing modular and maintainable code that can be easily shared and integrated across different projects. In this guide, we will show you how to overcome this challenge and create reusable C++ libraries with CMake. You will learn:</p><ul><li>The motivation and benefits of creating reusable libraries with CMake</li><li>The overview of the project structure and the main components</li><li>How to use external libraries and dependencies in your project</li><li>How to build and install your library and use it in another application</li></ul><p>By the end of this guide, you will have a solid understanding of how to create reusable libraries with CMake and how to apply these principles to your own projects.</p><h3>Motivation and Benefits</h3><p>Writing reusable libraries is a fundamental practice that fosters efficiency and collaboration in software development. With CMake as our build system, we gain the ability to encapsulate functionality into modular components, making it easier to share, integrate, and maintain code across various projects. This approach has many benefits, such as:</p><ul><li>Reducing code duplication and complexity</li><li>Ensuring code quality and consistency</li><li>Improving portability and compatibility</li><li>Enhancing performance and scalability</li><li>Facilitating testing and debugging</li></ul><p>According to a survey by JetBrains, CMake is the most popular build system among C++ developers, with 45% of respondents using it. CMake is also widely used by many open-source projects, such as Boost, LLVM, OpenCV, and TensorFlow. These facts demonstrate the popularity and usefulness of CMake in creating reusable libraries.</p><h3>Overview of the Project Structure</h3><p>The project exemplifies a practical use case, demonstrating how to create a reusable C++ library with CMake. The structure comprises multiple components, including:</p><ul><li><strong>my_libraries</strong>: The main library module that contains the primary reusable C++ library. It also utilizes external libraries through CMake’s find_package mechanism and demonstrates how to integrate and use the created library in a standalone application.</li><li><strong>external_libraries</strong>: The external dependencies module that illustrates how to manage and include external libraries seamlessly in the project.</li><li><strong>GitHub Repository</strong>: The complete source code and project files are available on my <a href="https://github.com/lucabonamini/example-library-cpp/tree/main">GitHub repository</a>, allowing developers to explore, experiment, and apply these principles to their own projects. Find the repository here.</li></ul><p>Each element is meticulously organized to showcase best practices in code organization, building, and integration. We will explain each component in detail in the following sections.</p><h3>Create a Library</h3><p>The project() command does more than just naming the project and specifying its version and language. It establishes a hierarchical scope for variables, offering a clear structure for configuring the entire build system.</p><pre>project(my_libraries VERSION 1.0 LANGUAGES CXX)</pre><p>CMake projects can involve multiple directories, each with its own CMakeLists.txt file. This hierarchical structure enables modular development, allowing developers to manage specific aspects of the project independently. Furthermore, the VERSION parameter aids in generating consistent version information across the project, crucial for documentation and compatibility management.</p><p>The find_package() command is a gateway to the rich ecosystem of external libraries. It goes beyond a simple check for presence; it orchestrates a complex interaction between your project and the external library.</p><pre>find_package(ExternalLibraries 1.0 REQUIRED EXACT)</pre><p>Here, we go beyond mere inclusion; we’re asserting precision with the REQUIRED EXACT options. This ensures not only that the required library is present but also that it matches the specified version precisely. A nuanced approach like this safeguards against unintended side effects from using incompatible versions. This command uses a Find&lt;Package&gt;.cmake module specific to ExternalLibraries, which is often provided by the library itself.</p><p>The add_library() command transforms your source code into a reusable unit, a library.</p><pre>add_library(MyLibraryA src/my_library_a.cpp)</pre><p>While adding source files is fundamental, it’s equally crucial to consider the library’s role in the broader project. Is it a standalone utility, an integral component, or an interface to other module? Clear intentions in your library design contribute to a more maintainable and comprehensible codebase.</p><p>The target_include_directories() command shapes how your library interfaces with the rest of the system.</p><pre>target_include_directories(MyLibraryA<br>  PUBLIC<br>    $&lt;INSTALL_INTERFACE:include&gt;<br>    $&lt;BUILD_INTERFACE:$(CMAKE_CURRENT_SOURCE_DIR)/include&gt;<br>)</pre><p>By segregating build and install interfaces, we’re future-proofing our library. Users, both during development and after installation, should seamlessly include our headers. This practice eases collaboration and ensures a consistent developer experience.</p><p>The $&lt;INSTALL_INTERFACE:include&gt; expression may seem cryptic, but it&#39;s a CMake generator expression. It dynamically adapts the include directory path based on whether the headers are being accessed during the build process or after installation. This ensures consistency in including headers, regardless of the context.</p><p>The target_link_libraries() command orchestrates the relationships between your library and external dependencies.</p><pre>target_link_libraries(MyLibraryA<br>  PUBLIC<br>    ExternalLibraries::ExternalLibraryA<br>  PRIVATE<br>    ExternalLibraries::ExternalLibraryB<br>)</pre><p>Understanding the distinction between PUBLIC and PRIVATE links is crucial. A PUBLIC link implies that users of your library should also link to ExternalLibraryA. This decision exposes a deliberate interface. On the other hand, a PRIVATE link to ExternalLibraryB indicates that this dependency is an internal implementation detail. These decisions shape how your library is perceived and used.</p><p>The install() command shapes the distribution of your library, preparing it for wider adoption.</p><pre>install(TARGETS MyLibraryA<br>  EXPORT MyLibraries-export<br>  LIBRARY DESTINATION lib<br>  ARCHIVE DESTINATION lib<br>)</pre><p>The EXPORT option in the install() command is significant. It generates an export set that captures information about the installed target, making it available for use in other projects. This encapsulates the entire library and its configuration, ensuring a seamless integration experience for external developers.</p><p>The CMakePackageConfigHelpers module elevates your library’s professionalism by generating configuration and version files.</p><pre>include(CMakePackageConfigHelpers)<br>write_basic_package_version_files(${CMAKE_CURRENT_SOURCE_DIR}/cmake/MyLibrariesConfigVersion.cmake<br>   VERSION ${PROJECT_VERSION}<br>   COMPATIBILITY SameMajorVersion)<br>install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/MyLibrariesConfigVersion.cmake<br>   DESTINATION &quot;lib/cmake/MyLibraries&quot;)</pre><p>The COMPATIBILITY SameMajorVersion option in write_basic_package_version_file communicates an essential compatibility guarantee. It asserts that projects with the same major version of your library should be compatible. This information is crucial for other developers relying on your library to make informed decisions about updates.</p><h3>Use a Library</h3><p>Now that we have crafted our reusable library, <em>MyLibraryA</em>, let’s explore how to seamlessly integrate it into our application, affectionately named <em>app</em>. This integration process involves configuring the application’s CMakeLists.txt file to leverage the functionalities provided by <em>MyLibraryA</em>.</p><p>The journey begins by establishing the foundational details of our application project. The project() command is employed to define the project name, version, and programming language.</p><pre>project(application VERSION 1.0 LANGUAGES CXX)</pre><p>Before delving into the application code, we must ensure that our application is aware of and properly configured to use <em>MyLibraryA</em>. The find_package() command is the gateway to achieving this. It seeks and configures the <em>MyLibraries</em> package, ensuring that our application can rely on the specific version of <em>MyLibraryA.</em></p><pre>find_package(MyLibraries 1.0 REQUIRED EXACT)</pre><p>This command sets the stage for our application to seamlessly integrate with <em>MyLibraryA</em>, paving the way for effective collaboration between the application and the reusable library.</p><p>With the project set up and the library located, the next step involves creating an executable target for our application using the add_executable() command. This command associates the source file src/application.cpp with the &#39;app&#39; executable.</p><pre>add_executable(app src/application.cpp)</pre><p>By executing this command, we establish <em>app</em> as the entry point for our application, where <em>MyLibraryA</em> will be utilized to enhance its functionality.</p><p>Now comes the critical moment of linking our application with <em>MyLibraryA</em>. The target_link_libraries() command accomplishes this linkage, ensuring that the &#39;app&#39; executable benefits from the features encapsulated in <em>MyLibraryA.</em></p><pre>target_link_libraries(app PRIVATE MyLibraries::MyLibraryA)</pre><p>The PRIVATE linkage specifies that <em>MyLibraryA</em> is an internal detail of our application. This distinction ensures that the application can leverage the library&#39;s capabilities without exposing them to external entities.</p><h3>Conclusion</h3><p>The journey through creating reusable C++ libraries with CMake unveils a powerful paradigm in software development, fostering efficiency, modularity, and collaboration. By leveraging CMake’s capabilities, developers can encapsulate functionality into modular components, resulting in code that is not only easy to share and integrate but also maintains a high level of consistency and portability.</p><p>The main points highlighted in this guide revolve around establishing a robust project structure, utilizing the <em>find_package</em> mechanism for external dependencies, and employing best practices in writing CMakeLists.txt files. The benefits of this approach are multifold: it reduces code duplication and complexity, ensures code quality and consistency, improves portability and compatibility across diverse projects, enhances performance and scalability, and facilitates testing and debugging.</p><p>Tips for writing CMakeLists.txt files include clear organization, thoughtful separation of build and install interfaces, and understanding the nuances of target linking for effective encapsulation. The generation of configuration and version files using <em>CMakePackageConfigHelpers</em> adds a layer of professionalism, making the library more accessible and integrable into various projects.</p><p>Experiment with the provided principles, apply them to your own projects, and wmbrace the power of creating reusable libraries with CMake!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/077c25a25cfc2d5c54c0cd1d87cb6574/href">https://medium.com/media/077c25a25cfc2d5c54c0cd1d87cb6574/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9f1180301" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/creating-reusable-libraries-with-cmake-c-a-step-by-step-guide-aa9f1180301">Creating reusable libraries with CMake &amp; C++: a Step-by-Step guide</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Multithreading and Thread-Safe Data Structure in C++]]></title>
            <link>https://levelup.gitconnected.com/understanding-multithreading-and-thread-safe-data-structure-in-c-04981f21edf5?source=rss-a63a387df30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/04981f21edf5</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Luca Bonamini]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 20:37:56 GMT</pubDate>
            <atom:updated>2024-12-27T18:25:20.627Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to implement a Thread-Safe data structure in C++</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCPbK3SMBq38AYsBblkw7g.jpeg" /></figure><p>Multithreading is a powerful concept in computer science that allows multiple threads to execute concurrently within a single program. Each thread represents an independent flow of execution, sharing the same resources, including memory space. While multithreading can significantly improve performance by leveraging multiple processor cores, it introduces challenges related to data safety consistency.</p><h4>The need for Thread-Safe Data Structures</h4><p>In a multithreaded environment, where multiple threads can access and modify shared data simultaneously, ensuring data integrity becomes crucial. Without proper synchronisation, concurrent operations on shared data structures can lead to race conditions, data corruption and other unpredictable behaviours.</p><p>One common scenario where thread safety is essential is in the implementation of concurrent data structures, such as queues. A thread-safe queue ensures that multiple threads can safely enqueue and dequeue elements without causing data loss, corruption or other synchronisation issues.</p><h4>Thread-Safe Queue Implementation</h4><p>In this article, we’ll delve into the technical details of implementing a thread-safe queue in C++. We’ll use the ThreadSafeQueue class, which provides safe access to a queue in a multithreaded environment.</p><p>Let’s analyze the key components of the ThreadSafeQueue implementation.</p><p><strong>Mutex and Locking</strong></p><p>The ThreadSafeQueue uses a std::mutex to provide exclusive access to the shared data structures. Mutexes ensure that only one thread can modify the internal state of the queue at any given time. The std::scoped_lock is employed to simplify the locking mechanism and ensure proper unlocking even in the presence of exceptions.</p><pre>mutable std::mutex mtx;</pre><p>The std::mutex is used to provide exclusive access to shared data. However, this approach involves locks, and it&#39;s important to note that there are also <strong>lock-free</strong> alternatives to implement thread-safe queues. Lock-free queues can provide better performance in certain scenarios by reducing contention, though they are more complex to implement and require careful use of atomic operations to ensure correctness.<br>Moreover, in the context of the ThreadSafeQueue, the mtx is marked as mutable to allow modification even when the ThreadSafeQueue is used in a const context. This means that the methods of the queue can be const, allowing users to call them even on const instances, without affecting the logical immutability of the queue&#39;s data.</p><p><strong>Condition Variable</strong></p><p>The std::condition_variable is used for efficient waiting and signaling between threads. It allows a thread to efficiently wait for a notification that data is available. When a new element is pushed into the queue, waiting threads are awakened through the condition variable.</p><pre>std::condition_variable data_cond;</pre><p><strong>Smart Pointers for Memory Management</strong></p><p>The use of std::shared_ptr is a key aspect of the implementation. Each element pushed in queue is dynamically allocated using std::allocate_shared. This ensures proper memory management and prevents memory leaks. The shared ownership semantics of std::shared_ptr allow multiple threads to safely access the same dynamically allocated memory.</p><pre>std::queue&lt;std::shared_ptr&lt;T&gt;&gt; data_queue;</pre><p>While the current implementation uses std::shared_ptr, <strong>shared pointers should be used with caution</strong> and ideally as a last resort. In general container classes, shared ownership can lead to indeterminate object lifetimes, introducing its own complexity and potential memory issues.</p><p>Given this, in most cases, <strong>std::unique_ptr</strong> should be preferred when ownership does not need to be shared.</p><p><strong>Push Operation</strong></p><p>The push operation is responsible for adding a new element to the queue. It allocates memory for the element, locks the mutex to ensure exclusive access, pushes the new element into the queue, and notifies waiting threads through the condition variable.</p><pre>void push(T new_value) {<br>    std::shared_ptr&lt;T&gt; data = std::make_shared&lt;T&gt;(std::move(new_value));<br>    std::scoped_lock lk(mtx);<br>    data_queue.push(data);<br>    data_cond.notify_one();<br>}</pre><p>Wait and Pop Operation</p><p>The wait_and_pop operation is designed for safely popping an element from the queue. It uses a std::unique_lock to lock the mutex and efficiently wait for a notification if the queue is empty. Once a notification is received, it retrieves the front element, pops it from the queue and return the shared pointer to the element.</p><pre>std::shared_ptr&lt;T&gt; wait_and_pop() {<br>    std::unique_lock lk(mtx);<br>    data_cond.wait(lk, [this] { return !data_queue.empty(); });<br>    std::shared_ptr&lt;T&gt; res = data_queue.front();<br>    data_queue.pop();<br>    return res;<br>}</pre><p><strong>Try Pop Operation</strong></p><p>The try_pop operation provides a non-blocking attempt to pop an elment from the queue. It locks the mutex, checks if the queue is empty, and if not it moves the value from the front of the queue and pops it. The use of std::scoped_lock ensures proper locking and unlocking.</p><pre>bool try_pop(T&amp; value) {<br>    std::scoped_lock lk(mtx);<br>    if (data_queue.empty()) {<br>        return false;<br>    }<br>    value = std::move(*data_queue.front());<br>    data_queue.pop();<br>    return true;<br>}</pre><p><strong>Example Usage</strong></p><p>Let’s illustrate the usage of the ThreadSafeQueue with multiple producet and consumer threads.</p><pre>int main() {<br>    ThreadSafeQueue&lt;int&gt; tsQueue;<br><br>    // Number of producers<br>    const int numProducers = 3;<br><br>    // Multiple producer threads pushing elements<br>    std::vector&lt;std::thread&gt; producers;<br>    for (int i = 0; i &lt; numProducers; ++i) {<br>        producers.emplace_back([&amp;tsQueue, i]() {<br>            for (int j = 0; j &lt; 10; ++j) {<br>                int value = i * 100 + j;<br>                tsQueue.push(value);<br>                std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Simulate some work<br>            }<br>        });<br>    }<br><br>    // Single consumer thread popping elements<br>    std::thread consumer([&amp;tsQueue]() {<br>        for (int i = 0; i &lt; 30; ++i) {<br>            auto value = tsQueue.wait_and_pop();<br>            if (value) {<br>                std::cout &lt;&lt; &quot;Dequeued: &quot; &lt;&lt; *value &lt;&lt; std::endl;<br>            }<br>        }<br>    });<br><br>    // Join all producer threads and the consumer thread<br>    for (auto&amp; producer : producers) {<br>        producer.join();<br>    }<br>    consumer.join();<br><br>    return 0;<br>}</pre><p>In the provided example, we simulate a scenario with multiple producer threads and a single consumer thread interacting with the ThreadSafeQueue. Here’s a breakdown of the example:</p><p><em>ThreadSafeQueue Initialization</em></p><p>An instance of ThreadSafeQueue&lt;int&gt; named tsQueue is created, serving as the shared data structure</p><pre>ThreadSafeQueue&lt;int&gt; tsQueue;</pre><p><em>Multiple Producers</em></p><p>A specified number of producer threads ( numProducers ) are spawned, each pushing ten unique values into the queue with a delay of 100 milliseconds between each push. The values are generated to demonstrate distinct contributions from each producer</p><pre>const int numProducers = 3;<br>for (int i = 0; i &lt; numProducers; ++i) {<br>    producers.emplace_back([&amp;tsQueue, i]() {<br>        for (int j = 0; j &lt; 10; ++j) {<br>            int value = i * 100 + j;<br>            tsQueue.push(value);<br>            std::this_thread::sleep_for(std::chrono::milliseconds(100));<br>        }<br>    });<br>}</pre><p><em>Single Consumer</em></p><p>A single consumer thread pops elements from the queue using the wait_and_pop operation. In this example, the consumer attempts to dequeue 30 elements.</p><pre>std::thread consumer([&amp;tsQueue]() {<br>    for (int i = 0; i &lt; 30; ++i) {<br>        auto value = tsQueue.wait_and_pop();<br>        if (value) {<br>            std::cout &lt;&lt; &quot;Dequeued: &quot; &lt;&lt; *value &lt;&lt; std::endl;<br>        }<br>    }<br>});</pre><p><em>Joining Threads</em></p><p>The main thread waits for all producer and consumer threads to complete their execution by calling join().</p><pre>for (auto&amp; producer : producers) {<br>    producer.join();<br>}<br>consumer.join();</pre><p>This example demonstrates the coordinated interaction between multiple producers and a single consumer using the ThreadSafeQueue. The synchronisation mechanisms and smart pointers ensure that the data structure remains thread-safe, preventing data loss or corruption during concurrent access.</p><p><strong>Conclusion</strong></p><p>In conclusion, the implementation of a thread-safe queue involves careful synchronisation using mutexes and condition variables. Smart pointers play a crucial role in managing dynamic memory and ensuring safe ownership across multiple threads. The ThreadSafeQueue presented here provides a robust solution for scenarios where multiple threads need to safely enqueue and dequeue elements, preventing data corruption and race conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04981f21edf5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-multithreading-and-thread-safe-data-structure-in-c-04981f21edf5">Understanding Multithreading and Thread-Safe Data Structure in C++</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>