-
Notifications
You must be signed in to change notification settings - Fork 0
Pripisnov #164
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Pripisnov #164
Changes from all commits
bfa456b
7fb7241
fa88e16
acde1a2
7b4ce8a
19016bb
86782d8
02f047d
d76d5a4
3cc4690
fa08237
5b0e09a
135a98d
9318361
575bdfd
f141c85
9899f7b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import time | ||
| import multiprocessing | ||
| import timeit | ||
|
|
||
|
|
||
| def is_prime(num): | ||
| if num <= 1: | ||
| return False | ||
| for i in range(2, int(num**0.5) + 1): | ||
| if num % i == 0: | ||
| return False | ||
| return True | ||
|
|
||
| def find_primes(start=3, end=100): | ||
| primes = [] | ||
| for num in range(start, end + 1): | ||
| if is_prime(num): | ||
| primes.append(num) | ||
| return primes | ||
|
|
||
|
|
||
| # Запуск три раза последовательно | ||
| for i in range(3): | ||
| start_time = time.time() | ||
| primes = find_primes(3, 10000) | ||
| end_time = time.time() | ||
| print(f"Простые числа от 3 до 10000 найдены за {end_time - start_time} секунд.") | ||
|
|
||
|
|
||
| # Запуск три раза в отдельных процессах | ||
| processes = [] | ||
| for i in range(3): | ||
| process = multiprocessing.Process(target=find_primes, args=(20001 + i * 10000, 30000 + i * 10000)) | ||
| processes.append(process) | ||
| process.start() | ||
| # process.join() - НЕ вызываем join здесь | ||
| for process in processes: | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. То что мы вызываем join() в вложенном цикле (фактически, для только что созданного процесса), сводит на нет весь параллелизм (проблема та же, что Вы описали в стр.35). |
||
| process.join() | ||
| #Для тестирования важно не забывать вызывать join() для потоков и процессов после их запуска, | ||
| # чтобы дождаться их завершения. Если вы забудете выполнить join(), | ||
| # основной поток (или процесс) может завершиться раньше, чем дочерние потоки (или процессы), | ||
| # и результаты выполнения могут быть непредсказуемыми или даже ошибочными. | ||
|
|
||
|
|
||
| # Замер времени исполнения функции find_primes для каждого диапазона | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Стоило посчитать суммарное время выполнения расчетов для всех диапазонов и сравнить с аналогичным временем для потоков и процессов. |
||
| time_seq_1 = timeit.timeit(lambda: find_primes(3, 10000), number=1) | ||
| time_seq_2 = timeit.timeit(lambda: find_primes(10001, 20000), number=1) | ||
| time_seq_3 = timeit.timeit(lambda: find_primes(20001, 30000), number=1) | ||
|
|
||
| print(f"Время выполнения последовательного варианта 1: {time_seq_1} сек.") | ||
| print(f"Время выполнения последовательного варианта 2: {time_seq_2} сек.") | ||
| print(f"Время выполнения последовательного варианта 3: {time_seq_3} сек.") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| import threading | ||
| import multiprocessing | ||
|
|
||
| def sum_integers(a, b): | ||
| return a + b | ||
|
|
||
| def concatenate_strings(a, b): | ||
| return a + b | ||
|
|
||
| def concatenate_lists(a, b): | ||
| return a + b | ||
|
|
||
| def parallel_sum(function, args_list): | ||
| results = [] | ||
| threads = [] | ||
|
|
||
| for args in args_list: | ||
| thread = threading.Thread(target=results.append, args=(function(*args),)) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Почему здесь выбраны именно потоки? Ведь из-за GIL в Python потоки не позволяют обеспечить параллельные вычисления! |
||
| threads.append(thread) | ||
| thread.start() | ||
|
|
||
| for thread in threads: | ||
| thread.join() | ||
|
|
||
| return results | ||
|
|
||
|
|
||
| # Пример использования функции parallel_sum | ||
| integer_args = [(1, 2), (3, 4), (5, 6)] | ||
| string_args = [('Hello', ' World'), ('Parallel', ' Processing'), ('Python', ' Multithreading')] | ||
| list_args = [([1, 2, 3], [4, 5, 6]), ([7, 8], [9, 10]), ([11, 12], [13, 14, 15])] | ||
|
|
||
| # Выполнение сложения для различных типов данных параллельно | ||
| results_integers = parallel_sum(sum_integers, integer_args) | ||
| results_strings = parallel_sum(concatenate_strings, string_args) | ||
| results_lists = parallel_sum(concatenate_lists, list_args) | ||
|
|
||
| print("Результаты сложения для integer:") | ||
| print(results_integers) | ||
|
|
||
| print("Результаты сложения для string:") | ||
| print(results_strings) | ||
|
|
||
| print("Результаты сложения для list:") | ||
| print(results_lists) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import threading | ||
|
|
||
| # Создаем объект Thread-local storage для каждого потока | ||
| thread_local_data = threading.local() | ||
|
|
||
| def print_private_data(): | ||
| # Получаем имя исполняемого потока | ||
| thread_name = threading.current_thread().name | ||
|
|
||
| # Проверяем, есть ли у потока приватные данные | ||
| if not hasattr(thread_local_data, 'private_data'): | ||
| thread_local_data.private_data = "Private data for " + thread_name | ||
|
|
||
| # Выводим имя потока и его приватные данные | ||
| print(thread_name + ": " + thread_local_data.private_data) | ||
|
|
||
| def run_threads(): | ||
| # Создаем и запускаем несколько потоков | ||
| threads = [] | ||
| for i in range(5): | ||
| thread = threading.Thread(target=print_private_data) | ||
| threads.append(thread) | ||
| thread.start() | ||
|
|
||
| # Дожидаемся завершения всех потоков | ||
| for thread in threads: | ||
| thread.join() | ||
|
|
||
| run_threads() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import socket | ||
|
|
||
|
|
||
| def main(): | ||
| host = '127.0.0.1' | ||
| port = 12345 | ||
|
|
||
| # Список зашифрованных слов | ||
| encrypted_words = ['xofa', 'ymno', 'zijk'] | ||
|
|
||
| # Создаем сокет и подключаемся к серверу | ||
| client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| client_socket.connect((host, port)) | ||
|
|
||
| # Отправляем список зашифрованных слов серверу | ||
| data = ','.join(encrypted_words) | ||
| client_socket.sendall(data.encode()) | ||
|
|
||
| # Получаем список расшифрованных слов от сервера | ||
| response = client_socket.recv(1024).decode() | ||
| decrypted_words = response.split(',') | ||
|
|
||
| print("Расшифрованные слова:") | ||
| for word in decrypted_words: | ||
| print(word) | ||
|
|
||
| # Закрываем соединение с сервером | ||
| client_socket.close() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import socket | ||
|
|
||
|
|
||
| # Словарь для дешифровки слов | ||
| dictionary = { | ||
| 'xofa': 'Привет', | ||
| 'ymno': 'Проверил', | ||
| 'zijk': 'Отлично' | ||
| } | ||
|
|
||
|
|
||
| def decrypt_words(encrypted_words): | ||
| decrypted_words = [dictionary.get(word, 'Unknown word') for word in encrypted_words] | ||
| return decrypted_words | ||
|
|
||
|
|
||
| def main(): | ||
| host = '127.0.0.1' | ||
| port = 12345 | ||
|
|
||
| # Создаем сокет и связываем его с хостом и портом | ||
| server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| server_socket.bind((host, port)) | ||
|
|
||
| # Слушаем подключения от клиентов | ||
| server_socket.listen(1) | ||
| print('Сервер запущен. Ожидание подключения клиента...') | ||
|
|
||
| # Принимаем подключение клиента | ||
| client_socket, client_address = server_socket.accept() | ||
| print('Подключен клиент:', client_address) | ||
|
|
||
| # Получаем данные от клиента (список зашифрованных слов) | ||
| data = client_socket.recv(1024).decode() | ||
| encrypted_words = data.split(',') | ||
|
|
||
| # Дешифруем слова и получаем список расшифрованных слов | ||
| decrypted_words = decrypt_words(encrypted_words) | ||
|
|
||
| # Отправляем список расшифрованных слов клиенту | ||
| response = ','.join(decrypted_words) | ||
| client_socket.sendall(response.encode()) | ||
|
|
||
| # Закрываем соединение с клиентом | ||
| client_socket.close() | ||
| server_socket.close() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import socket | ||
| import json | ||
|
|
||
|
|
||
| def send_user_info(username, age): | ||
| user_info = {'name': username, 'age': age} | ||
| message = json.dumps(user_info).encode() | ||
|
|
||
| client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| client_socket.connect(('localhost', 12345)) | ||
| client_socket.send(message) | ||
| client_socket.close() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # Примеры запуска клиентского приложения с различными пользователями | ||
| send_user_info('Alice', 25) | ||
| send_user_info('Bob', 30) | ||
| send_user_info('Eve', 22) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| import socket | ||
| import json | ||
|
|
||
|
|
||
| def start_server(): | ||
| server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| server_socket.bind(('localhost', 12345)) | ||
| server_socket.listen(5) | ||
| print("Сервер запущен и ждет подключения клиентов...") | ||
|
|
||
| connected_users = {} # Словарь для хранения информации о подключенных пользователях | ||
|
|
||
| while True: | ||
| conn, addr = server_socket.accept() | ||
| print(f"Подключился клиент: {addr}") | ||
|
|
||
| data = conn.recv(1024) | ||
| user_info = json.loads(data.decode()) | ||
| username = user_info.get('name', 'Unknown') | ||
| age = user_info.get('age', 'Unknown') | ||
|
|
||
| # Добавляем информацию о пользователе в словарь connected_users | ||
| connected_users[addr] = {'name': username, 'age': age} | ||
|
|
||
| # Выводим информацию о подключенных пользователях | ||
| print("Подключенные пользователи:") | ||
| for addr, user in connected_users.items(): | ||
| print(f"IP: {addr[0]}, Port: {addr[1]}, Name: {user['name']}, Age: {user['age']}") | ||
|
|
||
| conn.close() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| start_server() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import sqlite3 | ||
| import json | ||
|
|
||
|
|
||
| class SQLiteWrapper: | ||
|
|
||
| def __init__(self, db_name): | ||
| self.db_name = db_name | ||
| self.connection = None | ||
| self.cursor = None | ||
|
|
||
| def __enter__(self): | ||
| self.connection = sqlite3.connect(self.db_name) | ||
| self.cursor = self.connection.cursor() | ||
| return self | ||
|
|
||
| def __exit__(self, exc_type, exc_val, exc_tb): | ||
| if self.cursor: | ||
| self.cursor.close() | ||
| if self.connection: | ||
| self.connection.close() | ||
|
|
||
| def execute(self, query, params=None): | ||
| self.cursor.execute(query, params or ()) | ||
| self.connection.commit() | ||
|
|
||
| def select(self, query, params=None): | ||
| self.cursor.execute(query, params or ()) | ||
| rows = self.cursor.fetchall() | ||
| columns = [desc[0] for desc in self.cursor.description] | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Чтоб не заморачиваться с колонками (стр.30-31), достаточно перед исполнением запроса прописать self.cursor.row_factory = sqlite3.Row |
||
| results = [dict(zip(columns, row)) for row in rows] | ||
| return json.dumps(results, indent=4) | ||
|
|
||
| # Пример использования: | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Код в глобальной области видимости стоит помещать под |
||
| db_name = 'example.db' | ||
|
|
||
| # Создаем таблицу и вставляем данные | ||
| with SQLiteWrapper(db_name) as db: | ||
| db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)") | ||
| db.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 30)) | ||
| db.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Bob', 25)) | ||
|
|
||
| # Выбираем и выводим данные в формате JSON | ||
| with SQLiteWrapper(db_name) as db: | ||
| select_query = "SELECT * FROM users WHERE age > ?" | ||
| json_result = db.select(select_query, (25,)) | ||
| print(json_result) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| class Man: | ||
| def __init__(self, name): | ||
| self.name = name | ||
|
|
||
| def solve_task(self): | ||
| print("Я еще не готов") | ||
|
|
||
|
|
||
| # Пример использования класса | ||
| man = Man("John") | ||
| man.solve_task() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| import time | ||
| from random import randint | ||
|
|
||
| class Pupil: | ||
| def solve_task(self): | ||
| thinking_time = randint(3, 6) # Генерация случайного времени от 3 до 6 секунд | ||
| time.sleep(thinking_time) # Задержка выполнения программы на указанное количество секунд | ||
| print("I'm ready now!") | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Нет.. даже после того, как Pupil подумает, он всё равно должен сказать "Я еще не готов". |
||
|
|
||
|
|
||
| # Пример использования класса | ||
| pupil = Pupil() | ||
| pupil.solve_task() | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Этот код (в глобальной области видимости) будет выполняться во всех дочерних процессах.