Task: Multithreaded
Enter the labs/lab-06/tasks/multithreaded/ folder, run make skels, and go through the practice items below in the support/ directory.
-
Use the Makefile to compile
multithread.c, run it and follow the instructions.The aim of this task is to familiarize you with the
pthreadslibrary. In order to use it, you have to add#include <pthread.h>inmultithreaded.cand-lpthreadin the compiler options.The executable creates 5 threads besides the main thread, puts each of them to sleep for 5 seconds, then waits for all of them to finish. Give it a run and notice that the total waiting time is around 5 seconds since you started the last thread. That is the whole point - they each run in parallel.
-
Make each thread print its ID once it is done sleeping.
Create a new function
sleep_wrapper2()identical tosleep_wrapper()to organize your work. So far, thedataargument is unused (mind the__unusedattribute), so that is your starting point. You cannot changesleep_wrapper2()definition, sincepthreads_create()expects a pointer to a function that receives avoid *argument. What you can and should do is to pass a pointer to aintas argument, and then castdatatoint *insidesleep_wrapper2().Note: Do not simply pass
&ias argument to the function. This will make all threads to use the same integer as their ID.Note: Do not use global variables.
If you get stuck you can google
pthread exampleand you will probably stumble upon this. -
On top of printing its ID upon completion, make each thread sleep for a different amount of time.
Create a new function
sleep_wrapper3()identical tosleep_wrapper()to organize your work. The idea is to repeat what you did on the previous exercise and use the right argument forsleep_wrapper3(). Keep in mind that you cannot change its definition. Bonus points if you do not use the thread’s ID as the sleeping amount.