Practice Project: Simple Multithreaded Application
Practice Project: Simple Multithreaded Application
Welcome! With our recent lessons, you've gained a strong foundation in creating and managing threads, as well as understanding data sharing between threads using primitive approaches. Now, it's time to put all that knowledge into practice by building a simple multithreaded application.
Objective
In this project, you will create a basic program that simulates downloading files concurrently. This will involve:
-
Creating a
DownloaderClass:- The
Downloaderclass represents a task that downloads a file. - You will use threads to execute instances of this class concurrently, simulating asynchronous downloads.
- The
-
Simulating File Downloads with Delays:
- To make the downloads feel realistic, we'll introduce delays using
std::this_thread::sleep_for. - This will also help you understand how to manage and coordinate multiple threads working over time.
- To make the downloads feel realistic, we'll introduce delays using
-
Managing Multiple Threads:
- You'll learn how to start multiple download threads and ensure they complete correctly.
- Methods such as
join()anddetach()will be crucial here, ensuring that the main program waits for all downloads to finish before proceeding.
Here's a preview of what you'll be working towards:
Let's break down the code snippet above:
- The
Downloaderclass represents a task that downloads a file. It takes the file name as a parameter and simulates a download operation.- The
std::uniform_int_distributionobjectdistgenerates random delays between 100 and 200 milliseconds. - The
std::this_thread::sleep_forfunction pauses the thread for the specified duration.- Note, that we use
std::chrono::millisecondsto specify the duration in milliseconds and therndEngine_object is used to generate random numbers for the delay. We seed it withstd::random_device{}to ensure different sequences each time.
- Note, that we use
- The
operator()function is the entry point for the thread, where the download operation is performed.
- The
- In the
mainfunction:- We create two threads
t1andt2, each executing an instance of theDownloaderclass with different file names. - We use the
join()method to wait for both threads to complete before printing "All downloads completed".
- We create two threads
