19. Thread pools and return values

۰ نظر گزارش تخلف
Farnaz Baghban
Farnaz Baghban

Python Programming Thread Pools Exercise

Create a multithreaded application with ThreadPoolExecutor and 4 threads to compute the length of texts. You have a list with texts such as ['Adam', 'This is a text!', 'Albert Camus'] and you have a function that can calculate the length of a given string.

So the output should be something like this:

Adam - 4
This is a text! - 15
Albert Camus - 12
There may be several solutions: you can use submit and you can use map function as well. Let's use the map function!

Good luck!
=============================================
Python Programming - Thread Pools Solution

from concurrent.futures import ThreadPoolExecutor


def length_calculator(s):
time.sleep(2)
return len(s)


texts = ['Adam', 'This is a test!', 'Hey', 'Albert Camus']

with ThreadPoolExecutor(4) as executor:
for text, length in zip(texts, executor.map(length_calculator, texts)):
print(text + ' - ' + str(length))
===================================

نظرات

در حال حاضر امکان درج نظر برای این ویدیو غیرفعال است.

توضیحات

19. Thread pools and return values

۰ لایک
۰ نظر

Python Programming Thread Pools Exercise

Create a multithreaded application with ThreadPoolExecutor and 4 threads to compute the length of texts. You have a list with texts such as ['Adam', 'This is a text!', 'Albert Camus'] and you have a function that can calculate the length of a given string.

So the output should be something like this:

Adam - 4
This is a text! - 15
Albert Camus - 12
There may be several solutions: you can use submit and you can use map function as well. Let's use the map function!

Good luck!
=============================================
Python Programming - Thread Pools Solution

from concurrent.futures import ThreadPoolExecutor


def length_calculator(s):
time.sleep(2)
return len(s)


texts = ['Adam', 'This is a test!', 'Hey', 'Albert Camus']

with ThreadPoolExecutor(4) as executor:
for text, length in zip(texts, executor.map(length_calculator, texts)):
print(text + ' - ' + str(length))
===================================

آموزش