Simplifying, whereas a process abstracts a program execution, a thread abstracts the execution of a functionExplain this statement, taking into account the POSIX threads API.
pthread_create()
's prototype, the prototype of the function to be executed by the newly created thread is:
void *fun(void *arg)
void *
?fun
?Note To compile thread-based programs you must use the -pthread
compiler option. This ensures linking with the libpthread
library and with the thread-safe functions of the C library.
IMP. Follow an incremental code development approach. If you write all the code in a single go and only then compile it, you risk spending the following 15 minutes eliminating the compilation errors and the remaining class debugging it. Instead, you should add code step by step, compiling it and testing it, after each step.
Write a multi-threaded program that gets two integers from the command line and creates 4 threads, each of which computes the result of one arithmetic operation on those two integers different from the arithmetic operation computed by the other threads.
pid
and tid
and terminate returning an integer number between 1 and 3 and different from the value returned by the other threads. The main thread shall print in the standard out its pid
and the value returned by each of the other threads.pid
s of the different threads of a single program? And between its tids
?IMP. Do not forget to develop your code gradually. E.g.:
Write a new version of the previous program in which the number of threads, n
, is passed as a command line argument. Each thread, different from the main one, shall write its tid
and terminate returning an integer between 1
and n
different from the value returned by the remaining threads.
Hint: Use strtol
to convert the command line argument to an integer.
Test your program with different values for n
.
Write a multi-threaded program to initialize an integer array.
Your program shall accept 2 integer arguments: the number of array elements and the number of threads that will initialize the array, in that order.
The main thread shall process the command line arguments and create the threads that will initialize the array. After the initialization of the array, the main thread shall print all array elements.
The array shall be divided in parts of approximately the same size, and each of these parts shall be initialized by a different thread. Array element i
shall be initialized with the integer value i
.
Hint: Identify the information that each thread needs to process its sub-array and define a data structure that the main thread shall pass as an argument to the remainder threads.