thread and process
October 08, 2021
Thread
- smallest sequence of programmed instructions that can be managed independently by a scheduler.
- Has its own registers, PC. SP.
Process
- Instance of a computer program that is being executed
- A process can have one or more threads
Parallel Computing
- Run programs on one or more CPUs
- Multi-threading (shared memory)
- Multi-processing (Independent-memory)
1 | int a=1; |
Multithreading:
Shared memory, so variable can be accessed by both threads.
However, when multithreads write (non-atomic instruction) a shared variable, inconsistency could happen.
Problem:Access shared resources:
CPU may process instructions randomly.
1 | a += 1;//non-atomic |
1 | LOAD a,r |
1 | LOAD a,r1 |
1 | LOAD a,r1 |
To fix:
1 | void run() |
Note: only use lock when going to the critical section, becuase multithreading is much faster.
Communicate:
- shared variable
- semaphore, mutex, lock
Multiprocessing:
1 | int a=1; |
The pid returned by the fork() will not be 0 (0 as child process)
pid is the child process, should be 2+2;
pid is the parent process, should be 2+1;
Communicate:
- shared memory
- pipe
- socket
- RPC
Load Comments