Last active
December 5, 2019 23:22
-
-
Save amatellanes/685c1de2ab0ae168c788 to your computer and use it in GitHub Desktop.
Fibonnaci series by using threading module in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
from Queue import Queue | |
fibo_dict = {} | |
shared_queue = Queue() | |
input_list = [3, 10, 5, 7] | |
queue_condition = threading.Condition() | |
def fibonacci_task(condition): | |
with condition: | |
while shared_queue.empty(): | |
print("[{}] - waiting for elements in queue..".format(threading.current_thread().name)) | |
condition.wait() | |
else: | |
value = shared_queue.get() | |
a, b = 0, 1 | |
for item in range(value): | |
a, b = b, a + b | |
fibo_dict[value] = a | |
shared_queue.task_done() | |
print("[{}] fibonacci of key [{}] with result [{}]". | |
format(threading.current_thread().name, value, fibo_dict[value])) | |
def queue_task(condition): | |
print('Starting queue_task...') | |
with condition: | |
for item in input_list: | |
shared_queue.put(item) | |
print("Notifying fibonacci task threads that the queue is ready to consume...") | |
condition.notifyAll() | |
threads = [] | |
for i in range(4): | |
thread = threading.Thread(target=fibonacci_task, args=(queue_condition,)) | |
thread.daemon = True | |
threads.append(thread) | |
[thread.start() for thread in threads] | |
prod = threading.Thread(name='queue_task_thread', target=queue_task, args=(queue_condition,)) | |
prod.daemon = True | |
prod.start() | |
[thread.join() for thread in threads] | |
print("[{}] - Result {}".format(threading.current_thread().name, fibo_dict)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment