Intro 2 P Threads
Intro 2 P Threads
Intro 2 P Threads
2 using Pthreads
our first program with Pthreads
attributes, Pthread creating and joining
2 using Pthreads
our first program with Pthreads
attributes, Pthread creating and joining
process
registers
memory
heap
stack
static
code
heap
code
$ gcc -v
... output omitted ...
Thread model: posix
... output omitted ...
2 using Pthreads
our first program with Pthreads
attributes, Pthread creating and joining
$ make hello_pthreads
gcc -o /tmp/hello_pthreads hello_pthreads.c
$ /tmp/hello_pthreads
How many threads ? 5
creating 5 threads ...
waiting for threads to return ...
hello world from thread 0!
hello world from thread 2!
hello world from thread 3!
hello world from thread 1!
hello world from thread 4!
$
pthread_t t[n];
pthread_attr_t a;
int i,id[n];
for(i=0; i<n; i++)
{
id[i] = i;
pthread_attr_init(&a);
pthread_create(&t[i],&a,say_hi,(void*)&id[i]);
}
2 using Pthreads
our first program with Pthreads
attributes, Pthread creating and joining
2 using Pthreads
our first program with Pthreads
attributes, Pthread creating and joining
thread 0
set up thread 1 clean up
thread 2
✲
time
If the task is divided into many jobs stored in a queue,
then the threads grab the next job, compute the job,
and push the result onto another queue or data structure.
2 using Pthreads
our first program with Pthreads
attributes, Pthread creating and joining
typedef struct
{
int id; /* identification label */
int nb; /* number of jobs */
int *nextjob; /* index of next job */
int *work; /* array of nb jobs */
} jobqueue;
Every thread gets a job queue with two constants and two adrresses.
The constants are the identification number and the number of jobs.
The identification number labels the thread and is different for each
thread, whereas the number of jobs is the same for each thread.
The two addresses are the index of the next job and the work array.
Because we pass the addresses to each thread,
each thread can change the data the addresses refer to.
int i;
for(i=0; i<n; i++)
jobs->work[i] = 1 + rand() % 5;
return jobs;
}
2 using Pthreads
our first program with Pthreads
attributes, Pthread creating and joining
$ /tmp/process_jobqueue
How many jobs ? 4
4 jobs : 3 5 4 4
How many threads ? 2
creating 2 threads ...
waiting for threads to return ...
thread 0 requests lock ...
thread 0 releases lock
thread 1 requests lock ...
thread 1 releases lock
*** thread 1 does job 1 ***
thread 1 sleeps 5 seconds
*** thread 0 does job 0 ***
thread 0 sleeps 3 seconds
thread 0 requests lock ...
return 0;
}
return NULL;
}