Unix Threads
Unix Threads
- address space
- global variables
- open files,
-current working directory
-timers
-signals
-semaphores
-accounting information
-user and group Ids
-
-
thread ID
program counter
stack (for local variables and return addresses)
state
register set
child threads
priority
errno
where
- tid is the thread ID (returned by the call)
- attr is a set of attributes. Each thread has several attributes: its initial stack size, its priority,
whether it should be a daemon thread or not, and so on.
We can specify these attributes by initializing a pthread_attr_t variable that overrides the
defaults.
6
Normally the default values are taken, by specifying the attr argument as null pointer.
#include <pthread.h>
#include <pthread.h>
Detach
#include <pthread.h>
10
11
pthread_detach(pthread_self());
12
Posix mutexes
and condition variables
15
16
pthread_mutex_unlock (the_mutex);
18
#include "pthread.h"
#define NLOOP 5000
int
counter;
void
*doit(void *);
19
#include "pthread.h"
#define NLOOP 5000
int
counter;
/* this is incremented by the threads */
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
void
*doit(void *);
int main(int argc, char **argv)
{ pthread_t
tidA, tidB;
Pthread_create(&tidA, NULL, &doit, NULL);
Pthread_create(&tidB, NULL, &doit, NULL);
/*wait for both threads to terminate */
Pthread_join(tidA, NULL);
Pthread_join(tidB, NULL);
exit(0);
}
void * doit(void *vptr)
20
Example:
The Multiple-Producers/Single-Consumer
Problem:
Example: mutex-producer-consumer
#include
#define
#define
"unpipc.h"
MAXNITEMS
MAXNTHREADS
1000
100
22
void
/* include main */
int
main(int argc, char **argv)
{
int
i, nthreads, count[MAXNTHREADS];
pthread_t tid_produce[MAXNTHREADS], tid_consume;
if (argc != 3)
err_quit("usage: prodcons <#items> <#threads>");
nitems = min(atoi(argv[1]), MAXNITEMS);
23
nthreads = min(atoi(argv[2]), MAXNTHREADS);
Set_concurrency(nthreads + 1);
/* in Solaris 2.6: Thr_SetConcurrency(nthreads+1)
/* create all producers and one consumer */
for (i = 0; i < nthreads; i++) {
count[i] = 0;
pthread_create(&tid_produce[i], NULL,
produce, &count[i]);
}
/* wait for all producers */
for (i = 0; i < nthreads; i++) {
pthread_join(tid_produce[i], NULL);
24
26
Condition Variables:
Variables Waiting and Signaling
A mutex is for locking and a condition variable is for
waiting.
A condition variable is a variable of type:
pthread_cond_t
The associated functions are:
#include <pthread.h>
27
29
pthread_mutex_lock(&var.mutex);
set condition true
pthread_cond_signal(&var.cond);
pthread_mutex_unlock(&var.mutex);
"unpipc.h"
MAXNITEMS
MAXNTHREADS
1000000
100
31
Set_concurrency(nthreads + 1);
32
exit(0);
}
33
34
35
Additional functions
#include <pthread.h>
36