Introduction
In this project, you will learn how to use mutex to synchronize the printing of strings in a multi-threaded environment. You will modify an existing "Chaotic Typewriter" program to ensure that the strings are printed in the correct sequence without any intermixing of letters.
👀 Preview
$ gcc printer.c -o printer -lpthread
$ ./printer
helloworld
🎯 Tasks
In this project, you will learn:
- How to initialize a mutex in the
init()function - How to lock and unlock the mutex in the
printer()function to ensure exclusive access to the printing process - How to compile and run the modified program to observe the correct output
🏆 Achievements
After completing this project, you will be able to:
- Understand the importance of mutex in synchronizing access to shared resources in a multi-threaded program
- Apply mutex locking and unlocking techniques to coordinate the execution of multiple threads
- Troubleshoot and fix issues in a multi-threaded program to achieve the desired output
Initialize the Mutex
In this step, you will learn how to initialize the mutex in the init() function. Follow the steps below to complete this step:
- Open the
printer.cfile located in the/home/labex/project/directory. - In the code already given for the function
printer, the mutex is locked (pthread_mutex_lock(&mutex)) at the start to ensure exclusive access to the printing process. Once the string is fully printed, the mutex is unlocked (pthread_mutex_unlock(&mutex)), allowing the other thread to print. - Locate the
init()function and add the following code to initialize the mutex:
void init()
{
pthread_mutex_init(&mutex, NULL);
}
This initializes the mutex variable using the pthread_mutex_init() function, which is part of the POSIX Threads (pthreads) library. The second argument NULL specifies that we are using the default mutex attributes.
Compile and Run the Program
Now that you have completed the modifications to the printer.c file, you can compile and run the program.
- Open a terminal and navigate to the
/home/labex/project/directory. - Compile the program with the
-lpthreadflag to link the pthreads library:
gcc printer.c -o printer -lpthread
- Run the program:
./printer
You should now see the output:
helloworld
The strings "hello" and "world" are printed in sequence without any intermixing of the letters, as expected.
Congratulations! You have successfully modified the "Chaotic Typewriter" program to work as intended.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



