Recitation 1: Multitasking Kai Mast Threads vs. Processes Threads - - PowerPoint PPT Presentation

recitation 1 multitasking kai mast
SMART_READER_LITE
LIVE PREVIEW

Recitation 1: Multitasking Kai Mast Threads vs. Processes Threads - - PowerPoint PPT Presentation

Recitation 1: Multitasking Kai Mast Threads vs. Processes Threads Processes How to start? pthread_create() fork() (+ exec() ) Own Address Space? No Yes Can share memory? Yes No Can execute Yes Yes concurrently? (and other


slide-1
SLIDE 1

Recitation 1: Multitasking Kai Mast

slide-2
SLIDE 2

Threads vs. Processes

Threads Processes How to start? pthread_create() fork() (+exec() ) Own Address Space? No Yes Can share memory? Yes No Can execute concurrently? Yes Yes

(and other differences not relevant for the following...)

slide-3
SLIDE 3

A primer on concurrency

int main() { int i = fork(); if(i == 0) printf(“I’m the child! \n”) else printf(“I’m the parent! \n”); return 0; }

Two possible outputs: Or Why? bash:~ > ./a.out I’m the child I’m the parent bash:~ > ./a.out I’m the parent I’m the child

slide-4
SLIDE 4

A primer on concurrency

int main() { printf(“one \n”); int i = fork(); if(i == 0) printf(“two \n”) return 0; }

Only one possible output: Why? bash:~ > ./a.out

  • ne

two

slide-5
SLIDE 5

A visualization of concurrency

Parent Child

fork()

  • ne

two

Arrow implies “happens before”

slide-6
SLIDE 6

Question 2a)

Multiprocessing.

slide-7
SLIDE 7

What the Fork?

int result = 0; int main() { int i; for (i = 0; i < 2; i ++){ fork(); result++; printf(“result = %d\n”, result); } printf(“result = %d\n”, result); return 0; }

fork() duplicates the calling process

slide-8
SLIDE 8

Step 1

P1 P2

fork() 1 1 Note: This is only one possible schedule

slide-9
SLIDE 9

Step 2

P1 P2

fork() 1 1

P3

f

  • r

k ( ) f

  • r

k ( ) 2 2

P4

2 2 Note: This is only one possible schedule

slide-10
SLIDE 10

Step 3

P1 P2

fork() 1 1

P3

f

  • r

k ( ) f

  • r

k ( ) 2 2

P4

2 2 2 2 2 2 Note: This is only one possible schedule

slide-11
SLIDE 11

Question 2b)

Multithreading.

slide-12
SLIDE 12

Do not feel threatened by threads

int result = 0; pthread_t tid[2]; void *inc_result(void *ignore) { result++; printf(“result = %d\n”, result); fflush(stdout); return NULL; } int main() { for (int i = 0; i < 2; i ++){ pthread create(&tid[i], NULL, &inc_result, NULL); result++; printf(’result = %d\n’, result); } printf(“result = %d\n”, result); return 0; }

Creates a new thread in the same process Each child-thread will execute this function result is a global variable

slide-13
SLIDE 13

Step 1

T1 T2

pthread_create() 1 2 Note: This is only one possible schedule

slide-14
SLIDE 14

Step 2

T1 T2

pthread_create() 1 2 Note: This is only one possible schedule

T3

4 p t h r e a d _ c r e a t e ( ) 3 4