0% found this document useful (0 votes)
7 views

10. SP - Threads

The document provides an overview of processes and threads in system programming, highlighting the differences between them, including resource allocation and execution. It discusses the advantages of using threads, such as improved throughput and ease of information sharing, along with examples of thread creation, termination, and synchronization using mutexes. Additionally, it covers POSIX threads and provides code snippets for practical implementation.

Uploaded by

김나희
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

10. SP - Threads

The document provides an overview of processes and threads in system programming, highlighting the differences between them, including resource allocation and execution. It discusses the advantages of using threads, such as improved throughput and ease of information sharing, along with examples of thread creation, termination, and synchronization using mutexes. Additionally, it covers POSIX threads and provides code snippets for practical implementation.

Uploaded by

김나희
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

System Programming:

Threads

shchoi@kw.ac.kr

Sang Ho Choi (shchoi@kw.ac.kr)


School of Computer & Information Engineering
KwangWoon University
Process Review

• Process
– a program in execution
– program image + environment
➢ text(code) /data / stack / heap segment
➢ kernel data structure, address space, open files, ...
Process Review

/* test_program.c */
#include <stdio.h>
int a,b;
int glob_var = 3;

void test_func(void) {
int local_var, *buf;

buf = (int *) malloc(10,000 * sizeof(int));



}

int main(int argc, char *argv[]) {


int i = 1;
int local_var;

a = i + 1;
printf(“value of a = %d\n”, a); $ gcc –o test_program test_program.c
test_func();
}
Process Review

• $ ./test_program

Program Process

PCB

text
text
data Open files,
data
bss Terminal,
bss …
stack

heap

Disk
Memory
* bss: Block Started by Symbol
PCB: Process Control Block
Process Review

• UNIX is a multitasking system

$ ps –e
PID TTY TIME CMD
1? 00:00:00 init
2? 00:00:00 migration/0
3? 00:00:00 ksoftirqd/0
4? 00:00:00 watchdog/0
5? 00:00:00 migration/1
6? 00:00:00 ksoftirqd/1
7? 00:00:00 watchdog/1
8? 00:00:00 migration/2

29122 pts/9 00:00:00 bash
29151 ? 00:00:00 sshd
29170 ? 00:00:00 sshd
29171 pts/10 00:00:00 bash
30465 ? 00:00:00 httpd
$
Process Review

• UNIX is a time sharing system

process

Ready Queue

A B C A CPU
Process Review

• State of a process
Processes and Threads

• Processes
– Each process has a separate resources (separate
address memory space) to execute a program
– At least one thread of execution
➢can have multiple threads
– No protection between threads

• Threads
– An entity within a process that can be scheduled
for execution
– All threads of a process share the address space and
resources
Processes and Threads (cont.)

• Processes
– Process contains a single address space
– A separate address space of a process (protection)

• Threads
– A sequentially executing block within a process
(Sometimes called a lightweight process)
– No protection between threads
– A thread of a process (concurrency)
Threads concepts

• Thread
– An independent and schedulable execution unit
– A process can be divided into two or more running
threads
– A single thread of control(= a UNIX process)
➢Each process is doing only one thing at a time
– Multiple threads of control in a process
➢The process can do more than one thing at a time
– Multithreading is possible on even uni-processor
➢by time-division multiplexing
Threads concepts

• A typical example
– Apache web server

Server connection Client 1


thread 1

Server connection Client 2


thread 2

Program code & data is identical.


But, PC & stacks are different. Server connection Client 3
thread 3


Server Client M
thread N
Threads concepts

• Advantages of thread
– Easy to share information
➢the memory address space and file descriptors

– Throughput can be improved


➢The processing of independent tasks can be
interleaved

– More interactive
➢The separated threads can deal with user
input/output
Threads concepts

• Advantages of thread (cont.)


– The cost for creating a new process is low

fork() Process A pthread_create()


Process A
Thread 1
Global Global
Variables Process B
Variables
Global Process A
Code Variables Code Thread 2

Code
Stack Stack Stack

Stack
Threads concepts

• A thread-specific information
– Thread ID
– Register values
– Stack
– Scheduling priority
– A signal mask

• Sharable information among threads in a process


– Text section
– Global data
– Heap
– File descriptor
Threads concepts

• Process vs. thread


POSIX thread

• What is pthread?
– IEEE POSIX 1003.1c standards

• Pthread naming convention


– pthread_

• Compiling pthread program


– $ gcc –lpthread xxx.c
Thread identification

• Thread ID
– Identifier of thread (similar to process ID.)
– A thread ID is represented by pthread_t data type
➢Unsigned long integer in Linux
➢A pointer to the pthread structure in FreeBSD
Thread identification

#include <pthread.h>

pthread_t pthread_self(void);
Returns: the thread ID of the calling thread

• Obtain its own thread ID

#include <pthread.h>

int pthread_equal(pthread_t tid1, pthread_t tid2);


Returns: nonzero if equal, 0 otherwise

• Compare two thread IDs


Thread creation

#include <pthread.h>

int pthread_create(pthread_t *tidp,


const pthread_attr_t *attr,
void *(*start_rtn)(void), void *arg);
Returns: 0 if OK, error number on failure

• Create a new thread


– tidp is the ID of the newly created thread
– Execute start_rtn with arg as its argument
– attr is set to NULL for the default attributes
Thread creation

• Example

#include "apue.h"
#include <pthread.h>

pthread_t ntid;

void printids(const char *s)


{
pid_t pid;
pthread_t tid;

pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
(unsigned int)tid, (unsigned int)tid);
}
Thread creation

• Example (cont.)

void *thr_fn(void *arg)


{
printids("new thread: ");
return((void *)0);
}

int main(void)
{
int err;

err = pthread_create(&ntid, NULL, thr_fn, NULL);


if (err != 0)
err_quit("can't create thread: %s\n", strerror(err));
printids("main thread:");
sleep(1);
exit(0);
}
Thread creation

• 실행

In Solaris
When a thread is created, there is no guarantee which runs first.
$ ./a.out
main thread: pid 7225 tid 1 (0x1)
new thread: pid 7225 tid 4 (0x4)
$

In FreeBSD
$ ./a.out FreeBSD uses a pointer to the thread data structure for its thread ID.
main thread: pid 14954 tid 134529024 (0x804c000)
new thread: pid 14954 tid 134530048 (0x804c400)
$

In Linux
$ ./a.out
main thread: pid 17874 tid 140693894424320 (0x7ff5d9996700)
new thread: pid 17874 tid 140693886129920 (0x7ff5d91ad700)
$
Thread termination

• If any thread within a process call exit()?


– The entire process terminates

• A single thread can exit without terminating the


entire process
– The thread can simply return from the start routine
– The thread can be canceled by another thread in
the same process
– The thread can call pthread_exit()
Thread termination

#include <pthread.h>

void pthread_exit(void *rval_ptr);

• Terminates a calling thread


– rval_ptr is available to other threads in the process
calling the pthread_join()
Thread termination

#include <pthread.h>

int pthread_join(pthread_t thread, void **rval_ptr);


Returns: 0 if OK, error number on failure

• Suspends execution of the calling thread until the


target thread terminates
– It is similar to wait()
– rval_ptr argument
➢If not NULL, it contains the exit status of the target
thread
➢If we’re not interested in a return value, it is set to
NULL
Thread termination

• Example

#include "apue.h"
#include <pthread.h>

void *thr_fn1(void *arg)


{
printf("thread 1 returning\n");
return((void *)1);
}

void *thr_fn2(void *arg)


{
printf("thread 2 exiting\n");
pthread_exit((void *)2);
}
Thread termination

• Example (cont.)

int main(void)
{
int err;
pthread_t tid1, tid2;
void *tret;

err = pthread_create(&tid1, NULL, thr_fn1, NULL);


if (err != 0)
err_quit("can't create thread 1: %s\n", strerror(err));

err = pthread_create(&tid2, NULL, thr_fn2, NULL);


if (err != 0)
err_quit("can't create thread 2: %s\n", strerror(err));
Thread termination

• Example (cont.)

err = pthread_join(tid1, &tret);


if (err != 0)
err_quit("can't join with thread 1: %s\n", strerror(err));
printf("thread 1 exit code %d\n", (int)tret);

err = pthread_join(tid2, &tret);


if (err != 0)
err_quit("can't join with thread 2: %s\n", strerror(err));
printf("thread 2 exit code %d\n", (int)tret);

exit(0);
}
Thread termination

• 실행

$ ./a.out
thread 1 returning
thread 2 exiting
thread 1 exit code 1
thread 2 exit code 2
$
Thread termination

#include <pthread.h>

int pthread_cancel(pthread_t tid);


Returns: 0 if OK, error number on failure

• Cancel another thread in the same process


– Cause the thread with tid to behave as if it had
called pthread_exit()
– It doesn’t wait for the thread to terminate; it
merely makes the request
Thread termination

• Comparison of process and thread primitives

Process primitive Thread primitive Description


fork pthread_create Create a new flow of control
exit pthread_exit Exit from an existing flow of control
waitpid pthread_join Get exit status from flow of control
getpid pthread_self Get ID for flow of control
abort pthread_cancel Request abnormal termination of
flow of control
Thread synchronization

• A synchronization example
– Two threads try to modify the same variable
simultaneously
➢i is initialized to 5
➢Two threads perform “i++;”, respectively
Thread A Thread B

i++; i++;

– Simple statement “i++;” consists of several


instructions
➢Read the memory location into a register
➢Increment the value in the register
➢Write the new value back to the memory location
Thread synchronization

• A synchronization example
Mutex

• Mutex
– It is a lock that we set (lock) before accessing a
shared resource and release (unlock) when we’re
done
– While it is set, any other thread that tries to set it
will block until it is released
– If more than one thread is blocked when the mutex
is unlocked, then only one will be able to set the
lock
Mutex

#include <pthread.h>

int pthread_mutex_init(pthread_mutex_t *restrict mutex,


const pthread_mutexattr_t *restrict attr);
Return: 0 on success; otherwise, an error number

• Initialize a mutex
– initialize the mutex referenced by mutex with
attributes specified by attr
– attr is generally set to NULL

• Static initialization
– pthread_mutex_t mutex =
PTHREAD_MUTEX_INITIALIZER;
Mutex

#include <pthread.h>

int pthread_mutex_destroy(pthread_mutex_t *mutex);


Return: 0 on success; otherwise, an error number

• Destroy a mutex
– destroy the mutex object referenced by mutex
Mutex

#include <pthread.h>

int pthread_mutex_lock(pthread_mutex_t *mutex);


int pthread_mutex_unlock(pthread_mutex_t *mutex);
Return: 0 on success; otherwise, an error number

• Lock and unlock a mutex


– If the mutex is already locked, the calling thread
shall block until the mutex becomes available
Mutex

• Example (mutex_test.c)
#include <pthread.h>
#define NLOOP 50

int counter; // This is incremented by two 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);
}
Mutex

• Example

void *doit(void *vptr)


{
int i, val;

for (i = 0; i < NLOOP; i++)


{
pthread_mutex_lock(&counter_mutex);
val = counter;
printf("%d: %d\n", pthread_self(), val + 1);
counter = val + 1;
sleep(1);
pthread_mutex_unlock(&counter_mutex);
sleep(1);
}
return(NULL);
}
Mutex

• 실행
[kwangwoon@kw test]$ gcc –o mutex_test –lpthread mutex_test.c
[kwangwoon@kw test]$ ./mutex_test
1093278016: 1
1103767872: 2
1093278016: 3
1103767872: 4
1093278016: 5
1103767872: 6
1093278016: 7
1103767872: 8
1093278016: 9
1103767872: 10
1093278016: 11

1093278016: 99
1103767872: 100
[kwangwoon@kw test]$

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy