?print-pdf
' Created for
__init__(self [,args])
метода за да добавим собствени аргументи.run(self [,args])
метода за да укажем собствена функционалност при стартиране на нишка.
from threading import Thread, current_thread
from time import sleep
class CubTread(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, Verbose=None):
Thread.__init__(self, group, target, name, args, kwargs)
#self.value will store the value we need from thread's target
self.value = None
def run(self):
self.value = self._target(*self._args, **self._kwargs)
def join(self):
print(f'{self.name} res={self.value}')
return self.value
def cub(x):
return x**3
tr1 = CubTread(target=cub, args=(1,))
tr2 = CubTread(target=cub, args=(2,))
tr1.start(); tr2.start()
res1 = tr1.join()
res2 = tr2.join()
print(res1+res2)
import threading
import time
def worker():
global counter
for i in range(1_000_000):
counter += 1
counter = 0
# create some treads to count together:
thread_pool = []
for i in range(2):
tr = threading.Thread(target=worker)
thread_pool.append(tr)
print(f"Counter before start of {tr.name}: {counter}")
tr.start()
# wait for tread to finish:
for tr in thread_pool:
tr.join()
print("Workers counted:", counter)
import threading
def worker():
global counter
# lock the 'critical section':
lock.acquire()
for i in range(1_000_000):
counter += 1
lock.release()
counter = 0
lock = threading.Lock()
# create some treads to count together:
thread_pool = []
for i in range(5):
tr = threading.Thread(target=worker)
thread_pool.append(tr)
print(f"Counter before start of {tr.name}: {counter}")
tr.start()
# wait for tread to finish:
for tr in thread_pool:
tr.join()
print("Workers counted:", counter)