peri hokiperihokiclarustologisticsrimashaop.compola taktis menang gates of olympus x1000 perihokipemain perihoki bongkar trik jepep starlight princess x1000perihoki beri panduan lengkap bermain mahjong ways 2 pgsofttips cara penghasil uang pgsoft mahjong ways 2 perihokimahjong wins 3 perihoki memberikan penggali terbesarfenomena gates of olympus buka peluang besar bagi duta76cara dapat pola emas rahasia di duta7 wild west goldtrik menang pgsoft mahjong ways 2 modal receh maxwin duta76duta76 main pgsoft mahjong ways 2 di sela istirahatscatter hitam mahjong wins 3 spin pasti jepe duta76pola petir tersembunyi gates of olympus perihokipgsoft perkuat mahjong ways 2 di akun perihokiperihoki beri pola jitu mahjong wins 3 auto maxwin5 scatter jackpot driver ojolstrategi satpam scatter mahjongstrategi menang mahjong abc1131scatter emas pabrik wonosobomodal tipis scatter jadi cuanrtp mahjong ways supir menanginsting kuat bermain mahjong waysmengungkap keunggulan mahjong waysserunya mahjong bermodal kecil untung melimpahstrategi terbaik untuk menang mahjongterus main terus gacormenang banyak dengan scatter mahjong ways1menggali kehebatan mahjong winsrahasia nurul di mahjong waysstrategi mahjong yang mengubah permainan andateknik menang mahjong ways yang efektif

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 282

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_cookie_params(): Cannot change session cookie parameters when headers already sent

Filename: Session/Session.php

Line Number: 294

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 304

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 314

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 315

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 316

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 317

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 375

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: drivers/Session_files_driver.php

Line Number: 108

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_save_handler(): Cannot change save handler when headers already sent

Filename: Session/Session.php

Line Number: 110

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_start(): Cannot start session when headers already sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

Tìm hiểu về Multithreading trong Python - Freetuts
PYTHON CONCURRENCY
CÁC CHỦ ĐỀ
BÀI MỚI NHẤT
MỚI CẬP NHẬT

Thông báo: Download 4 khóa học Python từ cơ bản đến nâng cao tại đây.

Tìm hiểu về Multithreading trong Python

Trong bài viết này, bạn sẽ học cách sử dụng module threading trong Python để phát triển một chương trình đa luồng. Mình sẽ tìm hiểu cách mở rộng lớp Thread để tạo ra các luồng riêng biệt, giúp thực hiện các tác vụ một cách đồng thời. Bằng cách này, bạn có thể tăng hiệu suất và tối ưu hóa các hoạt động đòi hỏi nhiều tài nguyên, chẳng hạn như việc lấy giá cổ phiếu từ các trang web tài chính. Hãy cùng tìm hiểu cách triển khai và sử dụng threading trong Python qua các bước cụ thể và ví dụ minh họa chi tiết.

test php

banquyen png
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Mở rộng lớp Thread trong Python

Mình sẽ phát triển một chương trình đa luồng để lấy giá cổ phiếu từ trang Yahoo Finance.

Để thực hiện điều này, mình sẽ sử dụng hai gói bên thứ ba:

  • requests – để lấy nội dung của một trang web.
  • lxml – để chọn một phần tử cụ thể trong tài liệu HTML.

Đầu tiên, cài đặt các module requests và lxml bằng lệnh pip:

Bài viết này được đăng tại [free tuts .net]

pip install requests lxml

Tiếp theo, định nghĩa một lớp mới gọi là Stock kế thừa từ lớp Thread của module threading. Mình sẽ đặt lớp Stock trong file stock.py:

import threading

class Stock(threading.Thread):
   pass

Sau đó, triển khai phương thức __init__() để chấp nhận một ký hiệu và khởi tạo biến url dựa trên ký hiệu đó:

import threading
import requests
from lxml import html


class Stock(threading.Thread):
    def __init__(self, symbol: str) -> None:
        super().__init__()

        self.symbol = symbol
        self.url = f'https://finance.yahoo.com/quote/{symbol}'
        self.price = None

Ví dụ, nếu bạn truyền ký hiệu GOOG vào phương thức __init__(), URL sẽ là:

https://finance.yahoo.com/quote/GOOG

Sau đó, ghi đè phương thức run() của lớp Thread. Phương thức run() sẽ lấy nội dung từ self.url và lấy giá cổ phiếu:

class Stock(threading.Thread):
    def __init__(self, symbol: str) -> None:
        super().__init__()

        self.symbol = symbol
        self.url = f'https://finance.yahoo.com/quote/{symbol}'
        self.price = None

    def run(self):
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, như Gecko) Chrome/114.0.0.0 Safari/537.36"
        }
        response = requests.get(self.url, headers=headers)
        if response.status_code == 200:
            tree = html.fromstring(response.text)
            price_text = tree.xpath(
                '//*[@id="quote-header-info"]/div[3]/div[1]/div[1]/fin-streamer[1]/text()')
            if price_text:
                try:
                    self.price = float(price_text[0].replace(',', ''))
                except ValueError:
                    self.price = None

    def __str__(self):
        return f'{self.symbol}\t{self.price}'

Cách hoạt động:

  • Thực hiện yêu cầu đến URL sử dụng phương thức requests.get():
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, như Gecko) Chrome/114.0.0.0 Safari/537.36"
}
response = requests.get(self.url, headers=headers)

Lưu ý rằng nếu không có headers hợp lệ, Yahoo sẽ trả về mã 404 thay vì 200.

Nếu yêu cầu thành công, mã trạng thái HTTP là 200. Trong trường hợp này, mình lấy nội dung HTML từ phản hồi và chuyển nó vào hàm fromstring() của module html từ gói lxml:

if response.status_code == 200:
   tree = html.fromstring(response.text)

Mọi phần tử trên một trang web có thể được chọn bằng cách sử dụng XPath.

Để lấy XPath của một phần tử bằng Google Chrome, bạn nhấp chuột phải vào phần tử đó, chọn Inspect, sau đó nhấp chuột phải vào phần tử đã chọn, chọn Copy, và Copy XPath.

XPath của giá cổ phiếu tại thời điểm viết hướng dẫn này là:

//*[@id="quote-header-info"]/div[3]/div[1]/div[1]/fin-streamer[1]

Để lấy văn bản của phần tử, bạn thêm text() vào cuối XPath:

//*[@id="quote-header-info"]/div[3]/div[1]/div[1]/fin-streamer[1]/text()

Nếu Yahoo thay đổi cấu trúc trang, bạn cần thay đổi XPath tương ứng. Nếu không, chương trình sẽ không hoạt động như mong đợi:

price_text = tree.xpath('//*[@id="quote-header-info"]/div[3]/div[1]/div[1]/fin-streamer[1]/text()')

Sau khi lấy giá dưới dạng văn bản, mình xóa dấu phẩy và chuyển đổi nó thành một số:

if price_text:
    try:
        self.price = float(price_text[0].replace(',', ''))
    except ValueError:
        self.price = None

Cuối cùng, thêm phương thức __str__() để trả về chuỗi đại diện của đối tượng Stock:

import threading
import requests
from lxml import html


class Stock(threading.Thread):
    def __init__(self, symbol: str) -> None:
        super().__init__()

        self.symbol = symbol
        self.url = f'https://finance.yahoo.com/quote/{symbol}'
        self.price = None

    def run(self):
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, như Gecko) Chrome/114.0.0.0 Safari/537.36"
        }
        response = requests.get(self.url, headers=headers)
        if response.status_code == 200:
            tree = html.fromstring(response.text)
            price_text = tree.xpath(
                '//*[@id="quote-header-info"]/div[3]/div[1]/div[1]/fin-streamer[1]/text()')
            if price_text:
                try:
                    self.price = float(price_text[0].replace(',', ''))
                except ValueError:
                    self.price = None

    def __str__(self):
        return f'{self.symbol}\t{self.price}'

Sử dụng lớp Stock trong Python

Module main.py sau sử dụng lớp Stock từ module stock.py:

from stock import Stock

symbols = ['MSFT', 'GOOGL', 'AAPL', 'META']
threads = []

for symbol in symbols:
    t = Stock(symbol)
    threads.append(t)    
    t.start()
    

for t in threads:
    t.join()
    print(t)

Kết quả:

MSFT    253.67
GOOGL   2280.41
AAPL    145.86
META    163.27

Cách hoạt động:

Đầu tiên, nhập lớp Stock từ module stock.py:

from stock import Stock

Thứ hai, khởi tạo danh sách các ký hiệu:

symbols = ['MSFT', 'GOOGL', 'AAPL', 'META']

Thứ ba, tạo một luồng cho mỗi ký hiệu, khởi động nó, và thêm luồng vào danh sách threads:

threads = []
for symbol in symbols:
    t = Stock(symbol)
    threads.append(t)    
    t.start()

Cuối cùng, chờ tất cả các luồng trong danh sách threads hoàn thành và in ra giá cổ phiếu:

for t in threads:
    t.join()
    print(t)

Kết bài

Trong bài viết này, mình đã tìm hiểu cách xác định một lớp kế thừa từ lớp threading.Thread và ghi đè phương thức run() để thực hiện các tác vụ đa luồng trong Python. Việc sử dụng đa luồng không chỉ giúp tối ưu hóa hiệu suất mà còn cho phép mình thực hiện các công việc đòi hỏi nhiều tài nguyên một cách hiệu quả hơn. Qua ví dụ về việc lấy giá cổ phiếu từ Yahoo Finance, bạn đã thấy cách tạo, khởi động, và kết thúc các luồng, cũng như cách lấy và xử lý dữ liệu từ các luồng đó. Bằng cách nắm vững kỹ thuật này, bạn có thể áp dụng nó vào nhiều tình huống thực tế khác để cải thiện hiệu suất của các chương trình Python của mình.

Cùng chuyên mục:

Cách lưu trữ và tải lại Models trong PyTorch

Cách lưu trữ và tải lại Models trong PyTorch

Tìm hiểu về TensorBoard với PyTorch

Tìm hiểu về TensorBoard với PyTorch

Học chuyển giao (Transfer Learning) trong PyTorch Beginner

Học chuyển giao (Transfer Learning) trong PyTorch Beginner

Hướng dẫn cơ bản mạng Nơ-ron Tích Chập (CNN) trong PyTorch

Hướng dẫn cơ bản mạng Nơ-ron Tích Chập (CNN) trong PyTorch

Mạng Nơ-Ron truyền thẳng (Feed Forward Neural Network) trong PyTorch

Mạng Nơ-Ron truyền thẳng (Feed Forward Neural Network) trong PyTorch

Tìm hiểu Activation Functions trong PyTorch

Tìm hiểu Activation Functions trong PyTorch

Softmax và Cross Entropy trong PyTorch Beginner

Softmax và Cross Entropy trong PyTorch Beginner

Dataset Transforms trong PyTorch Beginner

Dataset Transforms trong PyTorch Beginner

Dataset và DataLoader trong PyTorch Beginner

Dataset và DataLoader trong PyTorch Beginner

Hồi quy Logistic trong PyTorch Beginner

Hồi quy Logistic trong PyTorch Beginner

Hồi quy tuyến tính trong PyTorch Beginner

Hồi quy tuyến tính trong PyTorch Beginner

Training Pipeline trong PyTorch Beginner

Training Pipeline trong PyTorch Beginner

Sử dụng Gradient Descent với Autograd trong PyTorch

Sử dụng Gradient Descent với Autograd trong PyTorch

Hướng dẫn về Tensor cơ bản trong PyTorch

Hướng dẫn về Tensor cơ bản trong PyTorch

Hướng dẫn cài đặt PyTorch với Deep Learning

Hướng dẫn cài đặt PyTorch với Deep Learning

LDA (Linear Discriminant Analysis) trong Python

LDA (Linear Discriminant Analysis) trong Python

Thuật toán AdaBoost trong Python

Thuật toán AdaBoost trong Python

Thuật toán K-Means Clustering trong Python

Thuật toán K-Means Clustering trong Python

Triển khai PCA bằng Python

Triển khai PCA bằng Python

Triển khai thuật toán Random Forest bằng Python

Triển khai thuật toán Random Forest bằng Python

Top