Sistem Operasi
Sistem Operasi
6
6
“Process
“Process
Synchronization”
Synchronization”
Synchronization
Synchronization
Antonius Rachmat C, S.Kom, M.Cs Antonius Rachmat C, S.Kom, M.Cs
P
l l P
i
P
l l P
i
Paralel Processing
Paralel Processing
Pa alel p ocessing is a sit ation in hich
• Paralel processing is a situation in which
two/more processor operate in unison.
– Executing instruction simultaneouslyExecuting instruction simultaneously
• Benefits: increase reliability & faster
processing
• Evolution:
– Job level: each job has its own processor and all processes and threads are run by the same all processes and threads are run by the same processor
– Process level: unrelated process, are
d l bl
assigned to any available processor
– Thread level: threads are assigned to avaliable processor
M
Si k
i
i
M
Si k
i
i
Mengapa Sinkronisasi
Mengapa Sinkronisasi
Sink oni
i dipe l k n nt k menghind i
• Sinkronisasi diperlukan untuk menghindari
terjadinya ketidak konsistenan data
akibat adanya akses data secara
akibat adanya akses data secara
konkuren
• Diperlukan adanya suatu mekanisme
p
y
untuk memastikan urutan / giliran
pengaksesan suatu data yang saling
bekerjasama sehingga terjadi
bekerjasama sehingga terjadi
sinkronisasi
• If we don’t make process synchronization:
If we don t make process synchronization:
– Race ConditionReview: Producer and
Review: Producer and
C
C
Consumer
Consumer
#define BUFFER_SIZE 10 typedef struct { . . . } item; item buffer[BUFFER_SIZE]; int in = 0; int out = 0; int counter = 0;P d
P d
Producer
Producer
while (true) {
/* produce an item and put in nextProduced */ while (count == BUFFER SIZE){( _ ){
} // do nothing
buffer [in] = nextProduced; in = (in + 1) % BUFFER SIZE; in = (in + 1) % BUFFER_SIZE; count++;
C
C
Consumer
Consumer
while (true) { while (count == 0){ while (count == 0){ } // do nothing nextConsumed = buffer[out]; nextConsumed = buffer[out];out = (out + 1) % BUFFER_SIZE;
count ; count--;
/* consume the item in nextConsumed
} }
A
i P
A
i P
Atomic Process
Atomic Process
Th t t
t
• The statements
counter++;
counter++;
counter--;
must be performed atomically.
• Atomic operation means an operation that
completes in its entirety without
completes in its entirety without
Bounded
Bounded Buffer
Buffer
Bounded
Bounded--Buffer
Buffer
• Perintah “count++” diimplementasikan pada bahasa mesin:
i t 1 t – register1 = counter
– register1 = register1 + 1 – counter = register1
Perintah “count ” diimplementasikan pada bahasa mesin: • Perintah “count--” diimplementasikan pada bahasa mesin:
– register2 = counter
– register2 = register2 – 1 counter register2
– counter = register2
• Jika kedua perintah tersebut berusaha mengakses nilai counter secara konkuren, maka dapat terjadi kesalahan pada nilai counter karena sifat bahasa mesin yang
pada nilai counter karena sifat bahasa mesin yang
menggunakan register untuk mengupdate nilai counter • Kesalahan nilai akhir counter dapat terjadi, tergantung
dari penjadwalan yang dilakukan terhadap proses yang p j y g p p y g dilakukan oleh produsen dan konsumen.
• Dengan kata lain, masalah tersebut belum tentu terjadi,
Mi l
Mi l
Misalnya
Misalnya
• Consider this execution interleaving with
“count = 5” initially:
t0: producer execute register1 = count {register1 = 5}
t1: producer execute register1 = register1 + 1 {register1 = 6} t1: producer execute register1 = register1 + 1 {register1 = 6}
t2: consumer execute register2 = count {register2 = 5}
t3: consumer execute register2 = register2 - 1 {register2 = 4}
t4: producer execute count = register1 {count = 6 } t5: consumer execute count = register2 {count = 4}
R
C
di i
R
C
di i
Race Condition
Race Condition
• Race condition: situasi dimana beberapa
proses mengakses dan memanipulasi
suatu data secara konkuren.
– Nilai akhir dari data tersebut tergantung dari proses mana yang terakhir mengubah data
• Untuk menghindari terjadinya situasi
tersebut, semua proses yang dapat
mengakses suatu data tertentu harus
disinkronisasi
C i i l S
i
C i i l S
i
Critical Section
Critical Section
Lebih da i sat p o e be lomb lomb
• Lebih dari satu proses berlomba-lomba
pada saat yang sama untuk menggunakan
data yang sama.
data yang sama.
• Setiap proses memiliki segmen kode yang
digunakan untuk mengakses data yang
g
g
y
g
digunakan secara bersama-sama.
– Segmen kode tersebut disebut criticalsection section.
• Masalahnya: menjamin bahwa jika suatu
proses sedang menjalankan critical
p
g
j
section, maka proses lain tidak boleh
Solusi masalah critical
Solusi masalah critical
ii
section
section
Mutual Exclusion
• Mutual Exclusion
– Tidak ada dua proses yang berada di critical section pada saat yang bersamaan.
T j di k j (P )
• Terjadi kemajuan (Progress)
– Jika tidak ada proses yang sedang berada di critical section, maka proses lain yang ingin menjalankan
iti l ti d t k k d l iti l ti critical section dapat masuk ke dalam critical section tersebut.
• Ada batas waktu tunggu (Bounded Waiting)
– Tidak ada proses yang menunggu selama-lamanya untuk masuk ke dalam critical section
– Assume that each process executes at a nonzero d
speed
– Tidak ada asumsi lain mengenai kecepatan relatif setiap proses ataupun jumlah CPU.
I
l
i
l i
I
l
i
l i
Implementasi solusi
Implementasi solusi
• Solusi perangkat lunak
– Dengan menggunakan algoritma-algoritma yang nilai kebenarannya tidak tergantung pada asumsi-asumsi lain, selain bahwa setiap proses berjalan pada kecepatan yang bukan nol
berjalan pada kecepatan yang bukan nol
• Solusi perangkat keras
T t d b b i t k i i
– Tergantung pada beberapa instruksi mesin tertentu, misalnya dengan me-non-aktifkan
interuppt atau dengan mengunci (lock) suatu interuppt atau dengan mengunci (lock) suatu
Implementasi software dan
Implementasi software dan
ii
asumsinya
asumsinya
Mi l h d d it P0 d P1 • Misal hanya ada dua proses, yaitu P0 dan P1.
• Struktur umum dari proses Pi (proses yang lain: Pj)
• Proses-proses tersebut boleh berbagi beberapa • Proses proses tersebut boleh berbagi beberapa
variabel yang sama untuk mensinkronisasikan
apa yang akan dilakukan oleh setiap proses
t b t
Algoritma 1
Algoritma 1
g
g
• Variabel yang digunakan bersama: – int turn; //pada awalnya turn = 0
– turn = i; //Pi dapat masuk ke critical section • Untuk proses Pi
• If P0 ingin akses critical section turn diset ke 0, if P1 juga akses, turn diset ke 1
Mutual exclusion but not progress nor bounded buffer
If P0 selesai menggunakan critical section, turn diset ke 1, tapi P1 tidak ingin masuk ke critical section jadi turn tidak akan diset ke tidak ingin masuk ke critical section, jadi turn tidak akan diset ke 0.
Algoritma 2
Algoritma 2
Algoritma 2
Algoritma 2
• Variabel yang digunakan bersama:
b l fl [2] – boolean flag[2];
• pada awalnya flag [0] = flag [1] = false – flag [i] = true; //Pi dapat
k k iti l ti masuk ke critical section
If P0 mengakses critical section P0 mengeset flag[0] ke True. Sementara P1 masih menggunakan critical section, P0 akan menunggu If P0 finish P0 akan set flag[0] ke false
menunggu. If P0 finish, P0 akan set flag[0] ke false.
Mutual exclusion but not progress nor bounded buffer
Tapi jika P0 & P1 ingin akses ke c itical section seca a konk en Tapi jika P0 & P1 ingin akses ke critical section secara konkuren, keduanya akan set flag[0] & flag[1] ke true, dan semua proses menunggu terus…
P
’ Al
i h
P
’ Al
i h
Peterson’s Algorithm
Peterson’s Algorithm
Th
h
• The two processes share two
variables:
– int
turn
;
– Boolean
flag[2];
g[ ];
• The variable turn
indicates whose
turn it is to enter the critical section
turn it is to enter the critical section.
• The flag
array is used to indicate if a
process is ready to enter the critical
process is ready to enter the critical
section. flag[i] = true implies that
process
P
is ready!
Algorithm for Process
Algorithm for Process
PP
Algorithm for Process
Algorithm for Process
PP
ii
while (true) {
flag[i] = TRUE; turn = j;
while ( flag[j] && turn == j);
CRITICAL SECTION
flag[i] = FALSE;
REMAINDER SECTION
}
Mutual exclusion progress and bounded buffer! Mutual exclusion, progress, and bounded buffer!
If P0 want to access critical section, P0 will set flag[0] to true and turn to P1.
B k
Al
i h
B k
Al
i h
Bakery Algorithm
Bakery Algorithm
C iti l ti f
Critical section for: n processes
• Sebelum memasuki critical section, setiap proses menerima sebuah nomor
menerima sebuah nomor.
• Yang memegang ID terkecil yang dilayani dahulu. • Skema penomoran selalu naik secara berurut, Skema penomoran selalu naik secara berurut,
contoh: 1, 2, 2, 2, 3, 3, 4, 5…
• Diperkenalkan pertama kali oleh Leslie
Lamport.
• Data yang digunakan bersama
boolean choosing [n]; – boolean choosing [n]; – int number [n];
• Struktur data diinisialisi awal ke false dan 0.
B k
Al
i h
B k
Al
i h
Bakery Algorithm
Bakery Algorithm
Si k
i
i
Si k
i
i
Sinkronisasi
Sinkronisasi
• Metode dalam sinkronisasi hardware • Metode dalam sinkronisasi hardware
– Processor Synchronous ( Disable Interrupt )
– Memory Synchronous ( Instruksi Test-And-Set )
• Interrupt used in Round Robin Algorithm with quantum • Interrupt used in Round Robin Algorithm, with quantum
time
• Processor synchronous
– Dengan men-disable interupsi (interrupt)Dengan men disable interupsi (interrupt) – Dalam lingkungan multiprocessor:
• Hanya satu processor bisa didisable interruptnya
• Memory synchronousMemory synchronous
– Instruksi Test-And-Set, Wait-Signal, dan Semaphore – Dalam lingkungan multiprocessor:
• Bisa dilakukan
• Semua processor tidak dapat memakai resource karena proteksi dilakukan di memory
T
T
A dS
A dS
d
d
J
J
Test
TestAndSet
AndSet dengan Java
dengan Java
M
l E l i
S
M
l E l i
S
Mutual Exclusion: Swap
Mutual Exclusion: Swap
HardwareData lock = new HardwareData(false); // a HardwareData lock = new HardwareData(false); // a shared lock
HardwareData key = new HardwareData(true); // my key
1st Process
2nd Process
while (true) {
key.set(true); // my key is now true truekey keytrue 2 Process false
do {
lock.swap(key);
// my key got lock’s content. 1st swap 2nd swap
I got it!
y y g
} while (key.get() == true); // this means lock was true locked!
criticalSection( ); // now in critical section code c t ca Sect o ( ); // o c t ca sect o code lock.set(false);
nonCriticalSection( ); // out of critical section
Lock
false true }
Mutual Exclusion: Memory
Mutual Exclusion: Memory
h
h
synchronous
synchronous
Kelebihan
• Kelebihan:
– Dapat diaplikasikan ke beberapa prosesor, dengan sharing memory
dengan sharing memory
– Simpel dan mudah diverifikasi
– Dapat digunakan untuk banyak critical section
• Kekurangan:
– Busy-waiting memakan processor time yang besar
besar
– Mungkin terjadi starvation – Deadlock
• Jika low priority process mendapat critical region dan higher priority process butuh juga, higher priority
process akan mendapat processor dan low priority k
S
h
S
h
Semaphore
Semaphore
• Invented by Djikstra (1960)
• Invented by Djikstra (1960)
• Semaphore digunakan untuk memberi
sinyal
y
• Non negative integer
• Jika proses menunggu sinyal, maka dia
akan ditunda sampai sinyal yg ditunggu
akan ditunda sampai sinyal yg ditunggu
tersebut terkirim
• Operasi: wait dan signal
p
g
• Wait dan signal operations tidak dapat
diinterupt
Queue digunakan untuk menahan proses
• Queue digunakan untuk menahan proses
proses yang sedang menunggu
semaphore
S
h
S
h
Semaphore
Semaphore
• Two standard operations modify S: wait() and signal() • Two standard operations modify S: wait() and signal()
– Originally called P() and V()
• Can only be accessed via two indivisible (atomic) operations operations – wait (S) { while S <= 0 // ; // no-op S--; }
jika s < 0 akan menunggu, lalu menjalankan proses lain
– signal (S) {
S++; }
memberikan kesempatan bagi para proses untuk p g p p berkompetisi mendapatkan semafore
S
h
W i
S
h
W i
S i l k
S i l k
Semaphore: Wait
Semaphore: Wait
Semaphore: Wait –
– non
non
i l k
i l k
spinlock
spinlock
S
h
Si
l
S
h
Si
l
Semaphore: Signal
Semaphore: Signal
C
h S
h
C
h S
h
Contoh Semaphore
Contoh Semaphore
Test(s) = if mutex > 0 then mutex = mutex – 1 Inc(s) mutex mutex + 1
I
l
i S
h
I
l
i S
h
Implementasi Semaphore
Implementasi Semaphore
Wi d
• Windows
– Fungsi yg dipakai adalah CreateSemaphore
Bi di k t k b t i j l h
– Biasanya digunakan untuk membatasi jumlah thread yang memakai suatu resource secara bersamaan
bersamaan
• Java
– Semafor di Java™ bersifat transparan oleh Semafor di Java bersifat transparan oleh programmer
• Java™ menyembunyikan Semafor dibalik konsep monitor
monitor
• Reserved Word yang dipakai Java™ adalah synchronized
Classical Problems of
Classical Problems of
S
h
i ti
S
h
i ti
Synchronization
Synchronization
• Bounded-Buffer Problem
• Readers and Writers Problem
• Readers and Writers Problem
• Dining-Philosophers Problem
B
d d B ff
B
d d B ff
Bounded Buffer
Bounded Buffer
Penge ti n temp t pen mp ng d t ng
• Pengertian: tempat penampung data yang
ukurannya terbatas
• Contoh: proses produsen dan
• Contoh: proses produsen dan
konsumen
• Masalah produsen-konsumen
Masalah produsen konsumen
– Produsen menaruh data pada buffer. Jika buffer tersebut sudah terisi penuh, maka produsen tidak melakukan apa apa dan produsen tidak melakukan apa-apa dan
menunggu sampai konsumen mengosongkan isi buffer.
K bil d d i b ff Jik
– Konsumen mengambil data dari buffer. Jika buffer tersebut kosong, maka konsumen tidak melakukan apa-apa dan menunggu sampai p p gg p
Penyelesaian dgn
Penyelesaian dgn
S
h
S
h
Semaphore
Semaphore
S
f
t
• Semafor mutex
– Menyediakan mutual exclusion untuk mengakses buffer
mengakses buffer
– Inisialisasi dengan nilai 1
• Semafor full
• Semafor full
– Menyatakan jumlah buffer yang sudah terisi – Inisialisasi dengan nilai 0
– Inisialisasi dengan nilai 0
• Semafor empty
– Menyatakan jumlah buffer yang kosong – Menyatakan jumlah buffer yang kosong – Inisialisasi dengan nilai n (jumlah buffer)
B
d d B ff
P d
B
d d B ff
P d
Bounded Buffer Producer
Bounded Buffer Producer
B
d d B ff
C
B
d d B ff
C
Bounded Buffer Consumer
Bounded Buffer Consumer
Contoh Producer &
Contoh Producer &
C
C
Consumer
Consumer
The Readers
The Readers--Writers
Writers
P bl
P bl
Problem
Problem
• Multiple readers or a single writer can
p
g
use DB.
writer
X
reader reader writerX
X
readerit reader writer reader reader writer reader reader
R d & W i
R d & W i
Reader & Writers
Reader & Writers
Dik t h i d
• Diketahui dua macam proses:
– Pembaca (reader) – Penulis (writer)Penulis (writer)
• Kedua jenis proses berbagi sumber daya penyimpanan yang sama, Misal: Basis data • Tujuan: data tidak korup dan inkonsisten • Kondisi:
P b d b b d
– Proses-proses pembaca dapat membaca sumber daya secara simultan
– Hanya boleh ada satu penulis menulis pada setiap saat – Bila ada yang menulis, tidak boleh ada yang membaca
Sh
d D
Sh
d D
Shared Data
Shared Data
• Data set
• Semaphore mutex
initialized to 1
• Semaphore mutex
initialized to 1,
tanda mutual exclusion
S
h
t
i iti li d t 1 t
d
• Semaphore wrt
initialized to 1, tanda
untuk menulis
• Integer readcount
initialized to 0,
tanda untuk membaca
Readers
Readers--Writers
Writers
Readers
Readers Writers
Writers
• The structure of a writer process while (true) { ( ) wait (wrt) ; // iti i f d // writing is performed signal (wrt) ; signal (wrt) ; }
R d
R d
W i
W i
Readers
Readers--Writers
Writers
• The structure of a reader process • The structure of a reader process
while (true) { wait (mutex) ; readcount ++ ; if (readcount == 1) wait (wrt) ; signal (mutex) // reading is performed wait (mutex) ; d readcount - - ; if (readcount == 0) signal (wrt) ; signal (mutex) ; } }
Di i
Phil
h
Di i
Phil
h
Dining Philosopher
Dining Philosopher
Diketahui: • Diketahui: – Mie (Data)– Sebuah meja bundar
– N filsuf duduk melingkar di meja bundar
– Antara dua filsuf terdapat
b h it
sebuah sumpit
– Didepan setiap filsuf terdapat semangkuk mie
S ti fil f h d t
• Setiap filsuf hanya dapat berada pada salah satu kondisi berikut:
– Berpikir – Lapar – MakanMakan
Di i
Phil
h
Di i
Phil
h
Dining Philosopher
Dining Philosopher
• Shared data
–Bowl of rice (data set)
–Bowl of rice (data set)
– Semaphore
chopstick [5]
initialized to 1
• Dua hal yang harus diperhatikan:
– Deadlock: Semua filsuf ingin makan dan
Deadlock: Semua filsuf ingin makan dan
telah memegang sumpit
– Starvation: Ada filsuf yang kelaparan
– Starvation: Ada filsuf yang kelaparan
The Structure of Philosopher i
The Structure of Philosopher i
Philosopher I
While (true) {
wait ( chopstick[i] ); //kanan
wait ( chopStick[ (i + 1) % 5] ); //kiri // eat
signal ( chopstick[i] ); //kanan
signal (chopstick[ (i + 1) % 5] ); //kiri
Picked up Waiting // think } Picked up Waiting A deadlock occurs! } A deadlock occurs!
K l
h
S
h
K l
h
S
h
Kelemahan Semaphore
Kelemahan Semaphore
• Termasuk Low Level
• Kesulitan dalam pemeliharaannya, karena
p
y ,
tersebar dalam seluruh program.
• Menghapus wait => dapat terjadi non-
Menghapus wait > dapat terjadi non
mutual exclusion.
• Menghapus signal => dapat terjadi
• Menghapus signal => dapat terjadi
deadlock
Error yang terjadi sulit untuk dideteksi
• Error yang terjadi sulit untuk dideteksi
S
M d l
S
M d l
System Model
System Model
• Assures that operations happen as a single
logical unit of work, in its entirety, or not
at all
• Challenge is assuring atomicity despite computer system failures
Transaction collection of instructions or
• Transaction - collection of instructions or operations that performs single logical
function
– Here we are concerned with changes to stable storage – disk
– Transaction is series of read and write operations – Terminated by commit (transaction successful) or
abort (transaction failed) operation
– Aborted transaction must be rolled back to undo any changes it performed
T
f S
M di
T
f S
M di
Types of Storage Media
Types of Storage Media
• Volatile storage – information stored
here does not survive system crashes
here does not survive system crashes
– Example: main memory, cache
• Nonvolatile storage – information
• Nonvolatile storage – information
usually survives crashes
Example: disk and tape – Example: disk and tape• Stable storage – information never lost
– Not actually possible, so approximated viareplication or RAID to devices with independent failure modes
LL
B
B
d R
d R
Log
Log--Based Recovery
Based Recovery
Re o d to t ble to ge info m tion bo t
• Record to stable storage information about
all modifications by a transaction
• Most common is
write-ahead logging
• Most common is
write-ahead logging
– Log on stable storage, each log record
describes single transaction write operation, i l di
including
• Transaction name • Data item name • Old value
• New value
– <T starts> written to log when transaction T<Ti starts> written to log when transaction Ti starts
Log
Log--Based Recovery
Based Recovery
Al
i h
Al
i h
Algorithm
Algorithm
U i th l t h dl l til
• Using the log, system can handle any volatile memory errors
– Undo(TUndo(Tii)) restores value of all data updated by Trestores value of all data updated by Tii
– Redo(Ti) sets values of all data in transaction Ti to new values
Undo(T ) and redo(T ) must be idempotent
• Undo(Ti) and redo(Ti) must be idempotent
– Multiple executions must have the same result as one execution
• If system fails, restore state of all updated data via log
If log contains <T starts> without <T commits> – If log contains <Ti starts> without <Ti commits>,
undo(Ti)
Ch k
i
Ch k
i
Checkpoints
Checkpoints
L
ld b
l
d
• Log could become long, and recovery
could take long
Ch
k
i t h t
l
d
• Checkpoints shorten log and recovery
time.
Ch k
i t h
• Checkpoint scheme:
1. Output all log records currently in volatile storage to stable storage
storage to stable storage
2. Output all modified data from volatile to stable storageg
3. Output a log record <checkpoint> to the log on stable storage