Skip to content

Instantly share code, notes, and snippets.

@ilkermanap
Last active September 25, 2019 18:02
Show Gist options
  • Save ilkermanap/fe7b41d20d5595fcc336fa2a9c56d87d to your computer and use it in GitHub Desktop.
Save ilkermanap/fe7b41d20d5595fcc336fa2a9c56d87d to your computer and use it in GitHub Desktop.
python thread example, python thread ornegi
from threading import Thread
import time
from random import randint
# Uc fonksiyon, uzun calisma icin sleep kullandik.
# her biri ayri bir thread olarak calisip, en uzun sure calisan bitince sonuclari yazacaktir.
def func1(a,b, result, idx):
sleepsec = randint(5,10)
print("func1, sleeping ", sleepsec)
time.sleep(sleepsec)
result[idx] = a+b
print("func1 finished, value ", a+b)
def func2(a,b, result, idx):
sleepsec = randint(5,10)
print("func2, sleeping ", sleepsec)
time.sleep(sleepsec)
result[idx] = a * b
print("func2 finished, value ", a*b)
def func3(a,b,c, result, idx):
sleepsec = randint(5,10)
print("func3, sleeping ", sleepsec)
time.sleep(sleepsec)
result[idx] = a - b + c
print("func3 finished, value ", a-b+c)
if __name__ == "__main__":
a = 10
b = 8
c = 4
threads = [] # fonksiyonlar thread seklinde bu diziye doldurulacaklar.
results = [None] *3 # sonuclari buraya dolduracagiz
threads.append(Thread(target=func1, args=(a,b,results,0,)))
# sonuclarin doldurulacagi dizi ve hangi indekse cevabi yazacagi parametre olarak veriliyor.
threads.append(Thread(target=func2, args=(a,b,results,1,)))
threads.append(Thread(target=func3, args=(a,b,c,results,2,)))
#threadleri baslat
for t in threads:
t.start()
#hepsinin sonlanmasini beklemesini sagla
for t in threads:
t.join()
#bu satira butun threadler bitince gelebilecek, sonuclari yaz
for r in results:
print(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment