Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions QUIS SISTER 1/1194002_Ahmad Fathoni R_/Barrier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#%%barrier = 3 thread akan nge print dalam waktu yang beda, tapi pas wait->bakal print bareng
# barrier akan menunggu thread lain untuk beres execute

from random import randrange
from threading import Barrier, Thread
from time import ctime, sleep

num_sleepers = 3
finish_line = Barrier(num_sleepers)
sleepers = ['Ahmad', 'Alwi', 'Abdul']

def sleeper():
name = sleepers.pop()
sleep(randrange(1, 8))
print('%s mulai tidur pada: %s ' % (name, ctime()))
finish_line.wait()
print('%s Bangun pada: %s ' % (name, ctime()))

def main():
threads = []
print('Selamat Tidur')
for i in range(num_sleepers):
threads.append(Thread(target=sleeper))
threads[-1].start()
for thread in threads:
thread.join()
print('Saatnya sahur')

if __name__ == "__main__":
main()

#%%barrier = 3 thread akan nge print dalam waktu yang beda, tapi pas wait->bakal print bareng
# barrier akan menunggu thread lain untuk beres execute

# import time
# import random
# import threading

# def f(b):
# time.sleep(random.randint(2, 10)) #
# print("{} execute ketika: {}".format(threading.current_thread().getName(), time.ctime()))
# b.wait() # akan wait thread lain untuk beres print
# print("{} keluar dari: {}".format(threading.current_thread().getName(), time.ctime()))

# barrier = threading.Barrier(3)
# for i in range(3):
# t = threading.Thread(target=f, args=(barrier,))
# t.start()
# %%
73 changes: 73 additions & 0 deletions QUIS SISTER 1/1194002_Ahmad Fathoni R_/Condition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import logging
import threading
import time

LOG_FORMAT = '%(asctime)s %(threadName)-17s %(levelname)-8s %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

items = []
condition = threading.Condition()
# Variabel condition digunakan untuk memungkinkan satu atau lebih thread untuk menunggu hingga diberitahukan oleh thread lain.


class Pembeli(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def beli(self):

with condition: # membungkus / enkapsulasi proses dengan metode dari variabel condition.

if len(items) == 0:
logging.info('Tidak ada makanan yang dapat dibeli')
condition.wait()

items.pop() # menghapus 1 item pada index
logging.info('Kamu membeli 1 item makanan')

condition.notify() # membangunkan thread yg menunggu variabel condition (jika ada)
# / memberi notif ke thread lain bahwa untuk sementara waktu proses disini sudah selesai

def run(self):
for i in range(20):
time.sleep(2) # jeda waktu untuk membeli
self.beli()


class Penjual(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def jual(self):

with condition: # membungkus / enkapsulasi proses dengan metode dari variabel condition.

if len(items) == 10:
logging.info('Di etalase terdapat {} item. Tidak cukup tempat. Produksi berhenti sementara'.format(len(items)))
condition.wait() # jika kondisinya sudah memenuhi tidak langsung berhenti, namun menunggu beberapa saat untuk proses thread lain

items.append(1) # akan bertambah 1 setiap prosesnya
logging.info('Terdapat {} item makanan saat ini'.format(len(items))) # mengembalikan item yang dihapus

condition.notify() # membangunkan thread yg menunggu variabel condition (jika ada)
# / memberi notif ke thread lain bahwa untuk sementara waktu proses disini sudah selesai

def run(self):
for i in range(20):
time.sleep(0.5) # jeda waktu produksi
self.jual()


def main():
pembeli = Penjual(name='Penjual') # (name) menginisialisasikan class Penjual dengan nama "penjual" agar dapat terbaca pada output
penjual = Pembeli(name='Pembeli') # (name) menginisialisasikan class Pembeli dengan nama "pembeli" agar dapat terbaca pada output

penjual.start()
pembeli.start()

penjual.join()
pembeli.join()


if __name__ == "__main__":
main()
47 changes: 47 additions & 0 deletions QUIS SISTER 1/1194002_Ahmad Fathoni R_/Event.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import logging
import threading
import time
import random

LOG_FORMAT = '%(asctime)s %(threadName)-17s %(levelname)-8s %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

items = []
event = threading.Event()


class Pelanggan(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def run(self):
while True:
time.sleep(2)
event.wait()
item = items.pop()
logging.info('Pelanggan memberi tahu: {} saya mampir {}'\
.format(item, self.name))

class Pedagang(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def run(self):
for i in range(5):
time.sleep(2)
item = random.randint(0, 100)
items.append(item)
logging.info('Pedagang memberi tahu: barang {} dibuat oleh {}'\
.format(item, self.name))
event.set()
event.clear()

if __name__ == "__main__":
t1 = Pedagang()
t2 = Pelanggan()

t1.start()
t2.start()

t1.join()
t2.join()
74 changes: 74 additions & 0 deletions QUIS SISTER 1/1194002_Ahmad Fathoni R_/MyThreadClass_lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import threading
import time
import os
from threading import Thread
from random import randint

# Lock Definition
threadLock = threading.Lock()

class AnggotaMhs (Thread):
def __init__(self, name, duration):
Thread.__init__(self)
self.name = name
self.duration = duration
def run(self):
#Acquire the Lock
threadLock.acquire()
print ("---> " + self.name + \
" Setiap orang Di kelas membawa bekal sebesar, "\
+ str(os.getpid()) + "\n")
time.sleep(self.duration)
print ("---> " + self.name + " over\n")
#Release the Lock
threadLock.release()


def main():
start_time = time.time()
# Thread Creation
mahasiswa1 = AnggotaMhs("mahasiswa#1 ", randint(1,10))
mahasiswa2 = AnggotaMhs("mahasiswa#2 ", randint(1,10))
mahasiswa3 = AnggotaMhs("mahasiswa#3 ", randint(1,10))
mahasiswa4 = AnggotaMhs("mahasiswa#4 ", randint(1,10))
mahasiswa5 = AnggotaMhs("mahasiswa#5 ", randint(1,10))
mahasiswa6 = AnggotaMhs("mahasiswa#6 ", randint(1,10))
mahasiswa7 = AnggotaMhs("mahasiswa#7 ", randint(1,10))
mahasiswa8 = AnggotaMhs("mahasiswa#8 ", randint(1,10))
mahasiswa9 = AnggotaMhs("mahasiswa#9 ", randint(1,10))

# mahasiswa Running
mahasiswa1.start()
mahasiswa2.start()
mahasiswa3.start()
mahasiswa4.start()
mahasiswa5.start()
mahasiswa6.start()
mahasiswa7.start()
mahasiswa8.start()
mahasiswa9.start()

# mahasiswa joining
mahasiswa1.join()
mahasiswa2.join()
mahasiswa3.join()
mahasiswa4.join()
mahasiswa5.join()
mahasiswa6.join()
mahasiswa7.join()
mahasiswa8.join()
mahasiswa9.join()

# End
print("End")

#Execution Time
print("--- %s seconds ---" % (time.time() - start_time))


if __name__ == "__main__":
main()




75 changes: 75 additions & 0 deletions QUIS SISTER 1/1194002_Ahmad Fathoni R_/MyThreadClass_lock_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import threading
import time
import os
from threading import Thread
from random import randint

# Lock Definition
threadLock = threading.Lock()

class AnggotaKelas (Thread):
def __init__(self, name, duration):
Thread.__init__(self)
self.name = name
self.duration = duration
def run(self):
#Acquire the Lock
threadLock.acquire()
print ("---> " + self.name + \
" Sedang Belajar, Dalam Kelas ini ada "\
+ str(os.getpid()) + "\n")
threadLock.release()
time.sleep(self.duration)
print ("---> " + self.name + " kelebihan\n")
#Release the Lock


def main():
start_time = time.time()

# Thread Creation
murid1 = AnggotaKelas("murid#1 ", randint(1,10))
murid2 = AnggotaKelas("murid#2 ", randint(1,10))
murid3 = AnggotaKelas("murid#3 ", randint(1,10))
murid4 = AnggotaKelas("murid#4 ", randint(1,10))
murid5 = AnggotaKelas("murid#5 ", randint(1,10))
murid6 = AnggotaKelas("murid#6 ", randint(1,10))
murid7 = AnggotaKelas("murid#7 ", randint(1,10))
murid8 = AnggotaKelas("murid#8 ", randint(1,10))
murid9 = AnggotaKelas("murid#9 ", randint(1,10))

# murid Running
murid1.start()
murid2.start()
murid3.start()
murid4.start()
murid5.start()
murid6.start()
murid7.start()
murid8.start()
murid9.start()

# murid joining
murid1.join()
murid2.join()
murid3.join()
murid4.join()
murid5.join()
murid6.join()
murid7.join()
murid8.join()
murid9.join()

# End
print("End")

#Execution Time
print("--- %s seconds ---" % (time.time() - start_time))


if __name__ == "__main__":
main()




60 changes: 60 additions & 0 deletions QUIS SISTER 1/1194002_Ahmad Fathoni R_/Rlock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import threading
import time
import random


class Kemasan:
def __init__(self):
self.lock = threading.RLock()
self.total_items = 0

def execute(self, value):
with self.lock:
self.total_items += value

def add(self):
with self.lock:
self.execute(1)

def remove(self):
with self.lock:
self.execute(-1)

def penambah(Kemasan, items):
print("N° {} items to ADD \n".format(items))
while items:
Kemasan.add()
time.sleep(1)
items -= 1
print("menamnbahkan satu barang -->{} barang yang akan ditambahkan \n".format(items))



def pengurang(Kemasan, items):
print("N° {} barang yang akan dihapus \n".format(items))
while items:
Kemasan.remove()
time.sleep(1)
items -= 1
print("menghapus satu barang -->{} barang yang dihapus \n".format(items))


def main():
items = 10
Kemasan = Kemasan()

t1 = threading.Thread(target=penambah, \
args=(Kemasan, random.randint(10,20)))
t2 = threading.Thread(target=pengurang, \
args=(Kemasan, random.randint(1,10)))

t1.start()
t2.start()


t1.join()
t2.join()


if __name__ == "__main__":
main()
Loading