Utilize POSIX Threads for Concurrency
In single-threaded applications, executing multiple blocking operations (such as disk I/O, network requests, or file downloads) sequentially can make a program painfully slow.
In this challenge, you are provided with a pre-compiled single-threaded program in ~/exercise/download. Your goal is to inspect its execution time, then refactor the code using POSIX Threads (pthreads) so that all file downloads run concurrently.
// ~/exercise/download.c
#include <stdio.h>
#include <unistd.h>
void download_file(const char *filename) {
printf("Downloading %s...\n", filename);
sleep(2); // Simulates network latency
printf("Finished downloading %s!\n", filename);
}
int main(void) {
download_file("file1.dat");
download_file("file2.dat");
download_file("file3.dat");
download_file("file4.dat");
return 0;
}
Task Instructions
- Observe the Blocking Program:
Navigate to
~/exerciseand run the provided./downloadprogram withtime. Notice how long it takes to download four files sequentially. - Refactor using POSIX Threads:
Modify
download.c(or create a new C file) to execute the file downloads concurrently using POSIX Threads (pthreads). - Compile and Verify:
Compile your updated code with
gcc(remember to link the threads library) and run the resulting executable. Verify that all downloads complete in ~2 seconds instead of the original execution time.
Hint: Compiling POSIX Threads
When compiling C programs that use pthreads, pass the -pthread flag to gcc to link the thread library and enable re-entrant header definitions.
Hint: POSIX Threads API
Include <pthread.h> in your C source file. Use pthread_create() to spawn worker threads for each download task and pthread_join() in the main thread to wait for all workers to finish.
Hint: Need a Refresher on Threads & Concurrency?
Check out the Linux Processes: Threads & Concurrency tutorial to learn more about thread management and POSIX thread functions.