CS139-lecture-20210923

Processes cont. #

Using fork and execl #

Consider this code

pid_t pid1, pid2; int status;
struct rusage usage;
if ((pid1=fork()))
{
	printf("I am parent %d; child is %d\n",getpid(),pid1);
	pid2=wait3(&status, 0, &usage);
	printf("exit code for %d is %d\n", pid2, status);
}
else
{
	execl("/bin/cat", "/bin/cat", "/csc/139/news/0001.txt", NULL);
	printf("we should never get here!\n");
} 

execl loads cat into the child’s memory space. When this child cat exits, it will never reach the subsequent printf.

This outputs

I am parent ...; child is ...
cat of 0001.txt
exit code for ... is ...

Another output possibility could be

cat of 0001.txt
I am parent ...; child is ...
exit code for ... is ...

#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
    printf("A\n");
    fork();
    printf("B\n");
    fork();
    printf("C\n");
    return 0;
}

Output

A
B
B
C
C
C
C

Threads #

So far, the processes that we have defined only have one thread of execution.

Idea: allow multiple threads of execution within the same process environment, to a large degree independent of each other.

image_2021-09-23-14-14-04 image_2021-09-23-14-16-47 image_2021-09-23-14-16-59

Threads maintain the same code, data, and open files in memory. Each thread will have its own registers and stack. Threads will share the heap. The thread’s register and stack will swap when switching to another thread.

Multithreading #

image_2021-09-23-14-26-30 image_2021-09-23-14-27-50

PCB

  • pid
  • state
  • pc
  • registers
  • open files

TCB (Thread control block)

  • state
  • pc
  • registers

image_2021-09-23-14-29-56 image_2021-09-23-14-30-22

The server will dispatch threads and then continue listening.

Benefits #

image_2021-09-23-14-35-22

Multicore programming #

image_2021-09-23-14-35-42 image_2021-09-23-14-36-35

Concurrency

  • supports more than one task making progress
  • single processor / core, scheduler providing concurrency
  • interleaves processes

Parallelism

  • implies a system can perform more than one task simultaneously

User threads and kernel threads #

image_2021-09-23-14-39-33

User processes

  • can only run in user mode
  • threads running in user mode are user processes

Kernel processes

  • can only run in kernel mode
  • threads running in kernel mode are kernel processes

image_2021-09-23-14-41-33