Pthreads
• One of three primary thread libraries is POSIX Pthreads
#include <stdio.h>
#include <stdlib.h>
int sum; / this data is shared by the thread(s) /
void runner(void param); / threads call this function /
int main(int argc, char argv[])
{
pthread t tid; / the thread identifier /
pthread attr t attr; / set of thread attributes */
/* set the default attributes of the thread */
pthread attr init(&attr);
/* create the thread */
pthread create(&tid, &attr, runner, argv[1]);
/* wait for the thread to exit */
pthread join(tid, NULL);
printf("sum = %d∖n", sum);
}
/ The thread will execute in this function /
void runner(void param)
{
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++)
sum += i;
pthread exit(0);
}
1. In a Pthreads program, separate threads begin execution in a specified function.
• In the example, 'runner()' function
2. When we execute the program, a single thread of control begins in main
3. main() creates a second thread that begins control in the runner() function.
a. Both threads share the global data sum.
b. 'pthread t tid' declares the identifier for the thread we will create
c. 'pthread attr t attr' declaration represents the attributes for the thread
d. 'pthread attr init(&attr)' function call is ued to set attributes is there
i. Because… we did not explicitly set any attributes, we use the default attributes provided.
e. separate thread is created with the pthread_create() function call.
i. pass the name of the function where the new thread will begin (in 'runner()" function)
ii. pass the integer parameter that was provided on the command line, argv[1]
4. Now the program has two threads(parent thread in main(), child thread performing in the runner())
5. program follows the thread create/join strategy,
a. after creating the summation thread, the parent thread will wait for it to terminate by calling the pthread join() function.
b. The summation thread will terminate when it calls the function pthread exit().
c. When summation thread has returned, the parent thread will output the value of the shared data sum.
Pthreads thread cancellation
Invoking pthread cancel()indicates only a request to cancel the target thread
actual cancellation depends on how the target thread is set up to handle the request.
When target thread is canceled, the call to pthread join() in the canceling thread returns.
Pthreads supports three cancellation modes….
Pthreads allows threads to disable or enable cancellation.
• a thread cannot be canceled if cancellation is disabled.
However, cancellation requests remain pending, so the thread can later enable cancellation and respond to the request.
The default cancellation
• type is deferred cancellation.
• cancellation occurs only when a thread reaches a cancellation point.
In Java…..
Thread worker;
...
/ set the interruption status of the thread /
worker.interrupt()