We will define two variables of the type pthread_t, by the names tid1 and tid2, to store two thread identifiers. These thread identifiers uniquely represent the threads in the system. We will invoke the pthread_create function twice to create two threads and assign their identifiers to the two variables tid1 and tid2, whose addresses are passed to the pthread_create function.
The two threads are created with the default attributes. We will execute the function runThread1 to create the first thread, and then the runThread2 function to create the second thread.
In the runThread1 function, we will display the message Running Thread 1 to indicate that the first thread was created and is running. In addition, we will invoke a for loop to display the sequence of numbers from 1 to 5 through the running thread. The sequence of numbers that are generated by the first thread will be prefixed by Thread 1.
Similarly, in the runThread2 function, we will display the message Running Thread 2 to inform that the second thread was also created and is running. Again, we will invoke a for loop to display the sequence of numbers from 1 to 5. To differentiate these numbers from the ones generated by thread1, these numbers are preceded by the text Thread 2.
We will then invoke the pthread_join method twice and pass our two thread identifiers, tid1 and tid2, to it. The pthread_join is invoked to make the two threads, and the main method waits until both of the threads have completed their respective tasks. When both of the threads are over, that is, when the functions runThread1 and runThread2 are over, a message saying that Both threads are over will be displayed in the main function.
Let's use GCC to compile the twothreads.c program, as follows:
D:\CBook>gcc twothreads.c -o twothreads
If you get no errors or warnings, that means the twothreads.c program has been compiled into an executable file, twothreads.exe. Let's run this executable file:
You may not get exactly the same output, as it depends on the CPU, but it is certain that both threads will exit simultaneously.
Voila! We've successfully completed multiple tasks with multiple threads. Now, let's move on to the next recipe!