6 Pthreads
6 Pthreads
CS 241 Lecture 8
(R: Chapter 12 pp 409-443)
Andrew Bennett
variables get copies of all variables share global variables share global variables
Parallelism (one
Concurrent Concurrent Sequential
CPU)
Parallelism May be executed Kernel threads may be executed
Sequential
(multiple CPUs) simultaneously simultaneously
int fd;
fd = *((int *)arg);
pthread_t pthread_self(void);
int pthread_equal(thread_t t1, pthread_t t2);
•The creating process (or thread) must provide a location for storage
of the thread id.
•We will discuss thread attributes later. For now, pass a null pointer to
indicate the default attributes.
•The third parameter is just the name of the program for the thread to
run.
•The last parameter is a pointer to the arguments.
int error;
int fd
pthread_t tid;
mq_timedreceiv
e * only when
putmsg
the command
sigpause
is F_SETLKW
08/13/24 CS241 © 2005 Roy Campbell, All R 21
ights Reserved
Passing parameters and returning
values
You can pass multiple parameters to a thread
by passing a pointer, such as an array, to
the thread when it is created.
Care must be taken in receiving return values.
The terminating thread passes a pointer to
the joining thread.
They share the same address space.
The return value must exist after the thread
terminates.
You cannot use an automatic variable in the
thread for the return value
pthread_attr_init
state pthread_attr_getdetachstate
pthread_attr_setdetachstate
stack pthread_attr_getguardsize
pthread_attr_setguardsize
pthread_attr_getstack
pthread_attr_setstack
scheduling pthread_attr_getinheritsched
pthread_attr_setinheritsched
pthread_attr_getschedparam
pthread_attr_setschedparam
pthread_attr_getschedpolicy
pthread_attr_setschedpolicy
pthread_attr_getscope
pthread_attr_setscope
if (error = pthread_attr_init(&tattr))
fprintf(stderr, "Failed to create attribute object: %s\n",
strerror(error));
else if (error = pthread_attr_setdetachstate(&tattr,
PTHREAD_CREATE_DETACHED))
fprintf(stderr, "Failed to set attribute state to detached: %s\n",
strerror(error));
else if (error = pthread_create(&tid, &tattr, processfd, &fd))
fprintf(stderr, "Failed to create thread: %s\n", strerror(error));
08/13/24 CS241 © 2005 Roy Campbell, All R 31
ights Reserved
The thread stack
You can set a location and size for the thread stack.
Some systems allow you to set a guard for the stack so that an
overflow into the guard area can generate a SIGSEGV signal.