Hướng dẫn python thread target class method - phương thức lớp mục tiêu chuỗi python

def post_test(tbid, line_num, response_time):
    """
    :param tbid: 参数id
    :return:
    """

    # 请求参数
    data = {'tbId': tbid, 'conditions': [{"key": "", "type": 1}], 'pageNum': 1, 'pageSize': 12}
    # 请求启动时间

    start = time.time()
    # post请求
    r = requests.post(url=url, data=json.dumps(data), headers=headers)
    # 请求结束时间
    end = time.time()
    # 保留两位小数
    finall_time = float('%.2f' % float(end - start))
    text = json.loads(r.text)
    # IO写入 只写入200的
    with open('text6.csv', 'a', newline='') as csvfile:
       if text['statusCode'] == '200':
        throughput = line_num * response_time / finall_time
        throughput = float('%.2f' % float(throughput))
        print('the perf_counter time of %s is %s and the content is %s ,throughput is %s' % (
            tbid, finall_time, json.loads(r.text), throughput))
        spamwriter = csv.writer(csvfile, dialect='excel')
        spamwriter.writerow([tbid] + [finall_time] + [throughput])
def start_thread(csv_name):
  tbid, response_time_sort, throughput_sort = read_csv(csv_name)
  print(tbid)
  line_num = len(tbid)
  response_times = 5

  for j in range(response_times):
    for i in tbid:
        t = threading.Thread(target=post_test, args=(i, line_num, response_times))
        t.start()
        t.join()

Tôi không biết cách gọi một phương thức trong một lớp, đặc biệt nếu nó có các tham số khởi tạo, nhưng bạn có thể thử phương thức này Tôi đang cố gắng sử dụng nhiều quy trình để giải quyết vấn đề này, đúng。

Chạy phương thức lớp Python trong nền thông qua luồng #PyThon #Parallel #TheReading #Asynchronous

Ở đây, một đoạn mã nhỏ để chạy các phương thức lớp như các luồng nền trong Python. Phương thức Run () thực hiện một số hoạt động mãi mãi và trong trường hợp sử dụng này, bạn muốn nó làm điều đó trong nền (cho đến khi ứng dụng chính chết), trong khi phần còn lại của ứng dụng tiếp tục hoạt động.

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')

Tôi sẽ hướng dẫn bạn qua những phần quan trọng nhất.

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
4 - Xác định chức năng thực thi nào. Xin lưu ý rằng tôi không có bất kỳ lập luận nào trong ví dụ này. Nếu bạn làm, chỉ cần chèn chúng vào Tuple Args.

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
5 - Chạy luồng ở chế độ daemon. Điều này cho phép ứng dụng chính thoát ra mặc dù chủ đề đang chạy. Nó cũng sẽ (do đó) cho phép sử dụng Ctrl+C để chấm dứt ứng dụng.

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
6 - Bắt đầu thực thi luồng.

Nguồn: http://sebastiandahlgren.se/2014/06/27/ricky-a-method-as-a-background-thread-in-python/

Mã nguồn: lib/threading.py Lib/threading.py


Mô-đun này xây dựng các giao diện luồng cấp cao hơn ở đầu mô-đun

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
7 cấp thấp hơn.

Đã thay đổi trong phiên bản 3.7: Mô -đun này được sử dụng là tùy chọn, giờ đây nó luôn có sẵn.This module used to be optional, it is now always available.

Xem thêm

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
8 cung cấp giao diện cấp cao hơn để đẩy các tác vụ vào một luồng nền mà không chặn thực thi luồng gọi, trong khi vẫn có thể truy xuất kết quả của họ khi cần thiết.

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
9 cung cấp giao diện an toàn luồng để trao đổi dữ liệu giữa các luồng đang chạy.

mydata = threading.local()
mydata.x = 1
0 cung cấp một cách tiếp cận thay thế để đạt được sự đồng thời cấp độ nhiệm vụ mà không yêu cầu sử dụng nhiều luồng hệ điều hành.

Ghi chú

Trong sê -ri Python 2.x, mô -đun này chứa các tên

mydata = threading.local()
mydata.x = 1
1 cho một số phương thức và chức năng. Chúng không được chấp nhận như Python 3.10, nhưng chúng vẫn được hỗ trợ để tương thích với Python 2.5 trở xuống.

Chi tiết triển khai CPython: Trong CPython, do khóa phiên dịch toàn cầu, chỉ một luồng có thể thực thi mã python cùng một lúc (mặc dù các thư viện định hướng hiệu suất nhất định có thể khắc phục giới hạn này). Nếu bạn muốn ứng dụng của mình sử dụng tốt hơn các tài nguyên tính toán của các máy đa lõi, bạn nên sử dụng

mydata = threading.local()
mydata.x = 1
2 hoặc
mydata = threading.local()
mydata.x = 1
3. Tuy nhiên, luồng vẫn là một mô hình thích hợp nếu bạn muốn chạy đồng thời nhiều tác vụ ràng buộc I/O.
In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use
mydata = threading.local()
mydata.x = 1
2 or
mydata = threading.local()
mydata.x = 1
3. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.

Tính khả dụng: Không phải emscripten, không phải wasi.: not Emscripten, not WASI.

Mô -đun này không hoạt động hoặc không có sẵn trên các nền tảng Webassugging

mydata = threading.local()
mydata.x = 1
4 và
mydata = threading.local()
mydata.x = 1
5. Xem các nền tảng Webassugging để biết thêm thông tin.WebAssembly platforms for more information.

Mô -đun này xác định các chức năng sau:

Chủ đề.Active_Count () ¶active_count()

Trả về số lượng đối tượng

mydata = threading.local()
mydata.x = 1
6 hiện còn sống. Số lượng được trả về bằng độ dài của danh sách được trả về bởi
mydata = threading.local()
mydata.x = 1
7.

Hàm

mydata = threading.local()
mydata.x = 1
8 là bí danh không dùng nữa cho chức năng này.

Chủ đề.Current_Thread ()current_thread()

Trả về đối tượng

mydata = threading.local()
mydata.x = 1
6 hiện tại, tương ứng với luồng điều khiển của người gọi. Nếu luồng điều khiển của người gọi không được tạo thông qua mô -đun
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
0, một đối tượng chủ đề giả với chức năng hạn chế được trả về.

Hàm

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
1 là bí danh không dùng nữa cho chức năng này.

Chủ đề.excepthook (args, /) ¶excepthook(args, /)

Xử lý ngoại lệ chưa được nâng lên bởi

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
2.

Đối số ARGS có các thuộc tính sau:

  • exc_type: loại ngoại lệ.

  • EXC_VALUE: Giá trị ngoại lệ, có thể là

    >>> from threading import Thread
    >>> t = Thread(target=print, args=[1])
    >>> t.run()
    1
    >>> t = Thread(target=print, args=(1,))
    >>> t.run()
    1
    
    3.

  • EXC_TRACEBACK: Traceback ngoại lệ, có thể là

    >>> from threading import Thread
    >>> t = Thread(target=print, args=[1])
    >>> t.run()
    1
    >>> t = Thread(target=print, args=(1,))
    >>> t.run()
    1
    
    3.

  • Chủ đề: Chủ đề nâng cao ngoại lệ, có thể là

    >>> from threading import Thread
    >>> t = Thread(target=print, args=[1])
    >>> t.run()
    1
    >>> t = Thread(target=print, args=(1,))
    >>> t.run()
    1
    
    3.

Nếu exc_type là

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
6, ngoại lệ bị bỏ qua âm thầm. Nếu không, ngoại lệ được in ra trên
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
7.

Nếu chức năng này tăng một ngoại lệ,

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
8 được gọi để xử lý nó.

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
9 có thể được ghi đè để kiểm soát các trường hợp ngoại lệ chưa được thực hiện bởi
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
2 được xử lý.

Lưu trữ exc_value bằng cách sử dụng móc tùy chỉnh có thể tạo chu kỳ tham chiếu. Nó nên được xóa rõ ràng để phá vỡ chu kỳ tham chiếu khi ngoại lệ không còn cần thiết.

Lưu trữ luồng bằng cách sử dụng một móc tùy chỉnh có thể hồi sinh nó nếu nó được đặt thành một đối tượng đang được hoàn thiện. Tránh lưu trữ chủ đề sau khi móc tùy chỉnh hoàn thành để tránh phục hồi các đối tượng.

Mới trong phiên bản 3.8.

Chủ đề .__ Excepthook__¶__excepthook__

Giữ giá trị ban đầu của

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
9. Nó được lưu để giá trị ban đầu có thể được khôi phục trong trường hợp chúng tình cờ được thay thế bằng các đối tượng bị hỏng hoặc thay thế.

Mới trong phiên bản 3.10.

Chủ đề.get_ident () ¶get_ident()

Trả về ‘định danh luồng, của luồng hiện tại. Đây là một số nguyên khác nhau. Giá trị của nó không có ý nghĩa trực tiếp; Nó được dự định là một cookie ma thuật được sử dụng, ví dụ: Để lập chỉ mục một từ điển của dữ liệu cụ thể theo luồng. Định danh luồng có thể được tái chế khi một luồng thoát ra và một luồng khác được tạo.

Mới trong phiên bản 3.3.

Chủ đề.get_native_id () ¶get_native_id()

Trả về ID luồng tích phân gốc của luồng hiện tại được gán bởi kernel. Đây là một số nguyên không âm. Giá trị của nó có thể được sử dụng để xác định duy nhất toàn bộ hệ thống chủ đề này (cho đến khi luồng kết thúc, sau đó giá trị có thể được tái chế bởi HĐH).

Tính khả dụng: Windows, FreeBSD, Linux, MacOS, OpenBSD, NetBSD, AIX.: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX.

Mới trong phiên bản 3.8.

Chủ đề .__ Excepthook__¶enumerate()

Giữ giá trị ban đầu của

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
9. Nó được lưu để giá trị ban đầu có thể được khôi phục trong trường hợp chúng tình cờ được thay thế bằng các đối tượng bị hỏng hoặc thay thế.

Mới trong phiên bản 3.10.main_thread()

Chủ đề.get_ident () ¶

Trả về ‘định danh luồng, của luồng hiện tại. Đây là một số nguyên khác nhau. Giá trị của nó không có ý nghĩa trực tiếp; Nó được dự định là một cookie ma thuật được sử dụng, ví dụ: Để lập chỉ mục một từ điển của dữ liệu cụ thể theo luồng. Định danh luồng có thể được tái chế khi một luồng thoát ra và một luồng khác được tạo.

Mới trong phiên bản 3.3.settrace(func)

Chủ đề.get_native_id () ¶

Trả về ID luồng tích phân gốc của luồng hiện tại được gán bởi kernel. Đây là một số nguyên không âm. Giá trị của nó có thể được sử dụng để xác định duy nhất toàn bộ hệ thống chủ đề này (cho đến khi luồng kết thúc, sau đó giá trị có thể được tái chế bởi HĐH).gettrace()

Tính khả dụng: Windows, FreeBSD, Linux, MacOS, OpenBSD, NetBSD, AIX.

Mới trong phiên bản 3.10.

Chủ đề.get_ident () ¶setprofile(func)

Trả về ‘định danh luồng, của luồng hiện tại. Đây là một số nguyên khác nhau. Giá trị của nó không có ý nghĩa trực tiếp; Nó được dự định là một cookie ma thuật được sử dụng, ví dụ: Để lập chỉ mục một từ điển của dữ liệu cụ thể theo luồng. Định danh luồng có thể được tái chế khi một luồng thoát ra và một luồng khác được tạo.

Mới trong phiên bản 3.3.getprofile()

Chủ đề.get_native_id () ¶

Mới trong phiên bản 3.10.

Chủ đề.get_ident () ¶stack_size([size])

Trả về ‘định danh luồng, của luồng hiện tại. Đây là một số nguyên khác nhau. Giá trị của nó không có ý nghĩa trực tiếp; Nó được dự định là một cookie ma thuật được sử dụng, ví dụ: Để lập chỉ mục một từ điển của dữ liệu cụ thể theo luồng. Định danh luồng có thể được tái chế khi một luồng thoát ra và một luồng khác được tạo.

Tính khả dụng: Windows, pthreads.: Windows, pthreads.

Nền tảng UNIX với hỗ trợ chủ đề POSIX.

Mô -đun này cũng xác định hằng số sau:

Chủ đề.timeout_max¶TIMEOUT_MAX

Giá trị tối đa được phép cho tham số thời gian chờ của các hàm chặn (

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
5,
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
6,
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
7, v.v.). Chỉ định thời gian chờ lớn hơn giá trị này sẽ tăng
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
8.

Mới trong phiên bản 3.2.

Mô -đun này xác định một số lớp, được chi tiết trong các phần dưới đây.

Thiết kế của mô -đun này dựa trên mô hình luồng Java. Tuy nhiên, trong đó Java tạo khóa và biến điều kiện hành vi cơ bản của mọi đối tượng, chúng là các đối tượng riêng biệt trong Python. Lớp Python từ

mydata = threading.local()
mydata.x = 1
6 hỗ trợ một tập hợp con về hành vi của lớp chủ đề Java,; Hiện tại, không có ưu tiên, không có nhóm chủ đề và chủ đề không thể bị phá hủy, dừng lại, treo, tiếp tục hoặc bị gián đoạn. Các phương thức tĩnh của lớp luồng Java, khi được thực hiện, được ánh xạ tới các hàm cấp mô-đun.

Tất cả các phương pháp được mô tả dưới đây được thực thi về mặt nguyên tử.

Dữ liệu địa lý địa lý

Dữ liệu địa lý địa chỉ là dữ liệu có giá trị cụ thể của luồng. Để quản lý dữ liệu địa lý, chỉ cần tạo một thể hiện là

while not predicate():
    cv.wait()
0 (hoặc một lớp con) và lưu trữ các thuộc tính trên đó:

mydata = threading.local()
mydata.x = 1

Các giá trị của phiên bản sẽ khác nhau đối với các luồng riêng biệt.

Classthreading.local¶ threading.local

Một lớp đại diện cho dữ liệu địa lý.

Để biết thêm chi tiết và các ví dụ mở rộng, hãy xem chuỗi tài liệu của mô -đun

while not predicate():
    cv.wait()
1.

Đối tượng chủ đề

Lớp

mydata = threading.local()
mydata.x = 1
6 đại diện cho một hoạt động được chạy trong một luồng điều khiển riêng biệt. Có hai cách để chỉ định hoạt động: bằng cách chuyển một đối tượng có thể gọi cho hàm tạo hoặc bằng cách ghi đè phương thức
# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 trong một lớp con. Không có phương thức nào khác (ngoại trừ hàm tạo) nên được ghi đè trong một lớp con. Nói cách khác, chỉ ghi đè các phương thức
while not predicate():
    cv.wait()
4 và
# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 của lớp này.

Khi một đối tượng luồng được tạo, hoạt động của nó phải được bắt đầu bằng cách gọi phương thức luồng ____ ____ ____. Điều này gọi phương thức

# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 trong một luồng điều khiển riêng biệt.

Khi hoạt động của chủ đề được bắt đầu, chủ đề được coi là ‘còn sống. Nó ngừng sống khi phương pháp

# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 của nó chấm dứt - thông thường hoặc bằng cách nâng cao một ngoại lệ chưa được xử lý. Phương pháp
while not predicate():
    cv.wait()
9 kiểm tra xem luồng có còn sống hay không.

Các chủ đề khác có thể gọi một phương thức chủ đề

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
0. Điều này chặn luồng gọi cho đến khi luồng có phương thức
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
0 được gọi là chấm dứt.

Một chủ đề có một tên. Tên có thể được chuyển cho hàm tạo và đọc hoặc thay đổi thông qua thuộc tính

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
2.

Nếu phương thức

# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 tăng ngoại lệ,
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
9 được gọi để xử lý nó. Theo mặc định,
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
9 bỏ qua âm thầm
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
6.

Một chủ đề có thể được gắn cờ dưới dạng chủ đề Daemon Daemon. Tầm quan trọng của lá cờ này là toàn bộ chương trình Python thoát ra khi chỉ còn lại các luồng daemon. Giá trị ban đầu được kế thừa từ chủ đề tạo. Cờ có thể được đặt thông qua thuộc tính

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
7 hoặc đối số trình xây dựng daemon.

Ghi chú

Chủ đề daemon đột ngột dừng lại khi tắt máy. Tài nguyên của họ (như các tệp mở, giao dịch cơ sở dữ liệu, v.v.) không được phát hành đúng. Nếu bạn muốn các chủ đề của mình dừng lại một cách duyên dáng, hãy làm cho chúng không phải là Daemonic và sử dụng một cơ chế báo hiệu phù hợp như

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
8.

Có một đối tượng chủ đề chính của người Viking; Điều này tương ứng với luồng điều khiển ban đầu trong chương trình Python. Nó không phải là một chủ đề daemon.

Có khả năng các đối tượng chủ đề giả của người Viking được tạo ra. Đây là các đối tượng chủ đề tương ứng với các chủ đề của người ngoài hành tinh, đó là các luồng điều khiển bắt đầu bên ngoài mô -đun luồng, chẳng hạn như trực tiếp từ mã C. Các đối tượng chủ đề giả có chức năng hạn chế; Họ luôn được coi là sống và daemonic, và không thể tham gia. Họ không bao giờ bị xóa, vì không thể phát hiện việc chấm dứt các chủ đề ngoài hành tinh.joined. They are never deleted, since it is impossible to detect the termination of alien threads.

Classthreading.Thread (Group = none, target = none, name = none, args = (), kwargs = {}, *, daemon = none) ¶ threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

Trình xây dựng này phải luôn luôn được gọi với các đối số từ khóa. Đối số là:

Nhóm phải là

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3; dành riêng cho phần mở rộng trong tương lai khi một lớp
with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()
0 được thực hiện.

Mục tiêu là đối tượng có thể gọi được được gọi bằng phương thức

# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7. Mặc định là
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, có nghĩa là không có gì được gọi.

Tên là tên chủ đề. Theo mặc định, một tên duy nhất được xây dựng theo biểu mẫu của chủ đề n, trong đó n là một số thập phân nhỏ, hoặc chủ đề của N (mục tiêu), trong đó, mục tiêu là

with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()
3 nếu đối số đích được chỉ định.

Args là một danh sách hoặc tuple của các đối số cho việc gọi mục tiêu. Mặc định là

with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()
4.

KWARGS là một từ điển của các đối số từ khóa cho việc gọi mục tiêu. Mặc định là

with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()
5.

Nếu không phải là

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, Daemon đặt rõ ràng liệu chủ đề có phải là daemonic hay không. Nếu
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3 (mặc định), thuộc tính daemon được kế thừa từ luồng hiện tại.

Nếu lớp con ghi đè hàm tạo, nó phải đảm bảo gọi hàm tạo lớp cơ sở (

with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()
8) trước khi làm bất cứ điều gì khác với luồng.

Đã thay đổi trong phiên bản 3.10: Sử dụng tên đích nếu đối số tên bị bỏ qua.Use the target name if name argument is omitted.

Đã thay đổi trong phiên bản 3.3: Đã thêm đối số daemon.Added the daemon argument.

bắt đầu()¶()

Bắt đầu hoạt động chủ đề.

Nó phải được gọi nhiều nhất một lần cho mỗi đối tượng chủ đề. Nó sắp xếp cho phương thức đối tượng

# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 được gọi trong một luồng điều khiển riêng biệt.

Phương pháp này sẽ tăng

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3 nếu được gọi nhiều hơn một lần trên cùng một đối tượng luồng.

chạy()¶()

Phương pháp đại diện cho hoạt động của chủ đề.

Bạn có thể ghi đè phương thức này trong một lớp con. Phương thức

# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 tiêu chuẩn gọi đối tượng có thể gọi được chuyển đến hàm tạo đối tượng là đối số đích, nếu có, với các đối số từ khóa và từ khóa được lấy từ các đối số ARGS và KWARGS, tương ứng.

Sử dụng danh sách hoặc tuple làm đối số ARGS được truyền cho

mydata = threading.local()
mydata.x = 1
6 có thể đạt được hiệu ứng tương tự.

Example:

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1

Tham gia (thời gian chờ = Không) ¶(timeout=None)

Đợi cho đến khi chủ đề chấm dứt. Điều này chặn luồng gọi cho đến khi luồng có phương thức

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
0 được gọi là chấm dứt - thông thường hoặc thông qua ngoại lệ chưa được xử lý - hoặc cho đến khi thời gian chờ tùy chọn xảy ra.

Khi đối số thời gian chờ có mặt chứ không phải

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, nó sẽ là một số điểm nổi chỉ định thời gian chờ cho hoạt động tính bằng giây (hoặc phân số của chúng). Vì
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
0 luôn trả về
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, bạn phải gọi
while not predicate():
    cv.wait()
9 sau
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
0 để quyết định xem có thời gian chờ xảy ra hay không - nếu luồng vẫn còn sống, cuộc gọi
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
0 đã hết thời gian.

Khi đối số thời gian chờ không có hoặc

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, thao tác sẽ chặn cho đến khi luồng kết thúc.

Một chủ đề có thể được nối nhiều lần.

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
0 tăng
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3 nếu một nỗ lực được thực hiện để tham gia vào luồng hiện tại vì điều đó sẽ gây bế tắc. Nó cũng là một lỗi đối với
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
0 một chủ đề trước khi nó được bắt đầu và cố gắng thực hiện việc nâng cao ngoại lệ tương tự.

Tên¶

Một chuỗi được sử dụng cho mục đích nhận dạng. Nó không có ngữ nghĩa. Nhiều luồng có thể được đặt cùng một tên. Tên ban đầu được đặt bởi hàm tạo.

getName () ¶ setName () ¶()setName()

API getter/setter không dùng nữa cho

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
2; sử dụng nó trực tiếp làm tài sản thay thế.

Không dùng nữa kể từ phiên bản 3.10.

nhận dạng nhận dạng

Định danh ’luồng của chủ đề này hoặc

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3 nếu luồng chưa được bắt đầu. Đây là một số nguyên khác nhau. Xem hàm
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
06. Định danh luồng có thể được tái chế khi một luồng thoát ra và một luồng khác được tạo. Mã định danh có sẵn ngay cả sau khi chủ đề đã thoát.

native_id¶

ID luồng (

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
07) của chủ đề này, như được chỉ định bởi HĐH (kernel). Đây là một số nguyên không âm hoặc
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3 nếu chủ đề chưa được bắt đầu. Xem hàm
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
09. Giá trị này có thể được sử dụng để xác định duy nhất toàn bộ hệ thống luồng cụ thể này (cho đến khi luồng kết thúc, sau đó giá trị có thể được tái chế bởi HĐH).

Ghi chú

Tương tự như ID xử lý, ID luồng chỉ hợp lệ (được bảo đảm toàn bộ hệ thống) kể từ khi luồng được tạo cho đến khi luồng bị chấm dứt.

Tính khả dụng: Windows, FreeBSD, Linux, MacOS, OpenBSD, NetBSD, AIX, DragonFlyBSD.: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD.

Mới trong phiên bản 3.8.

is_alive () ¶()

Trả lại liệu chủ đề còn sống.

Phương pháp này trả về

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 ngay trước khi phương thức
# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 bắt đầu cho đến khi phương thức
# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
7 chấm dứt. Hàm mô -đun
mydata = threading.local()
mydata.x = 1
7 trả về danh sách tất cả các luồng còn sống.

đại sắc lý

Một giá trị boolean cho biết liệu luồng này có phải là một luồng daemon hay không (

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10) hay không (
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15). Điều này phải được đặt trước khi
while not predicate():
    cv.wait()
6 được gọi, nếu không
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3 được nâng lên. Giá trị ban đầu của nó được kế thừa từ chủ đề tạo; Chủ đề chính không phải là một luồng daemon và do đó tất cả các luồng được tạo trong luồng chính mặc định là
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
7 =
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15.

Toàn bộ chương trình Python thoát ra khi không còn chủ đề không phải là Daemon.

isdaemon () ¶ setdaemon () ¶()setDaemon()

API getter/setter không dùng nữa cho

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
7; sử dụng nó trực tiếp làm tài sản thay thế.

Không dùng nữa kể từ phiên bản 3.10.

nhận dạng nhận dạng

Định danh ’luồng của chủ đề này hoặc

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3 nếu luồng chưa được bắt đầu. Đây là một số nguyên khác nhau. Xem hàm
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
06. Định danh luồng có thể được tái chế khi một luồng thoát ra và một luồng khác được tạo. Mã định danh có sẵn ngay cả sau khi chủ đề đã thoát.

native_id¶

Khóa cũng hỗ trợ giao thức quản lý bối cảnh.context management protocol.

Khi có nhiều hơn một luồng bị chặn trong

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 đang chờ trạng thái chuyển sang mở khóa, chỉ có một luồng tiến hành khi cuộc gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 đặt lại trạng thái để mở khóa; Một trong những chủ đề đang chờ tiến hành không được xác định và có thể thay đổi giữa các triển khai.

Tất cả các phương pháp được thực thi về mặt nguyên tử.

Classthreading.Lock¶ threading.Lock

Lớp thực hiện các đối tượng khóa nguyên thủy. Khi một luồng đã có được một khóa, các nỗ lực tiếp theo để có được khối nó, cho đến khi nó được phát hành; Bất kỳ chủ đề có thể phát hành nó.

Lưu ý rằng

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
32 thực sự là một chức năng nhà máy trả về một phiên bản hiệu quả nhất của lớp khóa bê tông được hỗ trợ bởi nền tảng.

có được (chặn = true, thời gian chờ = -1) ¶(blocking=True, timeout=- 1)

Có được một khóa, chặn hoặc không chặn.

Khi được gọi với đối số chặn được đặt thành

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 (mặc định), chặn cho đến khi khóa được mở khóa, sau đó đặt nó thành khóa và trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10.

Khi được gọi với đối số chặn được đặt thành

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15, không chặn. Nếu một cuộc gọi với chặn được đặt thành
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 sẽ chặn, hãy trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15 ngay lập tức; Nếu không, đặt khóa thành khóa và trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10.

Khi được gọi với đối số thời gian chờ điểm nổi được đặt thành giá trị dương, khối trong nhiều nhất số giây được chỉ định bởi thời gian chờ và miễn là khóa không thể có được. Một đối số thời gian chờ của

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
39 chỉ định một sự chờ đợi không giới hạn. Nó bị cấm chỉ định thời gian chờ khi chặn là
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15.

Giá trị trả về là

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 nếu khóa được thu được thành công,
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15 nếu không (ví dụ: nếu thời gian chờ hết hạn).

Đã thay đổi trong phiên bản 3.2: Tham số thời gian chờ là mới.The timeout parameter is new.

Đã thay đổi trong phiên bản 3.2: Việc thu nhận khóa hiện có thể bị gián đoạn bởi các tín hiệu trên POSIX nếu việc triển khai luồng cơ bản hỗ trợ nó.Lock acquisition can now be interrupted by signals on POSIX if the underlying threading implementation supports it.

phóng thích()¶()

Phát hành khóa. Điều này có thể được gọi từ bất kỳ chủ đề nào, không chỉ các luồng đã có được khóa.

Khi khóa được khóa, đặt lại để mở khóa và quay lại. Nếu bất kỳ luồng nào khác bị chặn chờ khóa được mở khóa, hãy cho phép chính xác một trong số chúng tiến hành.

Khi được gọi trên một khóa không khóa, một

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3 được nâng lên.

Không có giá trị quay lại.

bị khóa () ¶()

Trả lại

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 Nếu khóa được thu thập.

Đối tượng rlock

Khóa reentrant là một nguyên thủy đồng bộ hóa có thể có được nhiều lần bởi cùng một luồng. Trong nội bộ, nó sử dụng các khái niệm về việc sở hữu chủ đề của người Hồi giáo và cấp độ đệ quy, ngoài trạng thái bị khóa/mở khóa được sử dụng bởi các khóa nguyên thủy. Ở trạng thái bị khóa, một số chủ đề sở hữu khóa; Trong trạng thái mở khóa, không có chủ đề sở hữu nó.

Để khóa khóa, một luồng gọi phương thức

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 của nó; Điều này trả về một khi luồng sở hữu khóa. Để mở khóa khóa, một luồng gọi phương thức
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 của nó. ________ 122/________ 123 cặp cuộc gọi có thể được lồng; Chỉ có
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 cuối cùng (
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 của cặp ngoài cùng) đặt lại khóa để mở khóa và cho phép một luồng khác bị chặn trong
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 để tiến hành.

Khóa reentrant cũng hỗ trợ giao thức quản lý bối cảnh.context management protocol.

Lớp học.Rlock¶threading.RLock

Lớp này thực hiện các đối tượng khóa Reentrant. Một khóa reentrant phải được phát hành bởi chủ đề có được nó. Khi một luồng đã có được một khóa reentrant, cùng một luồng có thể có được nó một lần nữa mà không chặn; Chủ đề phải phát hành nó một lần cho mỗi lần nó có được nó.

Lưu ý rằng

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
52 thực sự là một chức năng nhà máy trả về một phiên bản hiệu quả nhất của lớp rlock cụ thể được hỗ trợ bởi nền tảng.

có được (chặn = true, thời gian chờ = -1) ¶(blocking=True, timeout=- 1)

Có được một khóa, chặn hoặc không chặn.

Khi được gọi với đối số chặn được đặt thành

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 (mặc định), chặn cho đến khi khóa được mở khóa, sau đó đặt nó thành khóa và trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10.

Khi được gọi với đối số chặn được đặt thành

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15, không chặn. Nếu một cuộc gọi với chặn được đặt thành
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 sẽ chặn, hãy trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15 ngay lập tức; Nếu không, đặt khóa thành khóa và trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10.

Khi được gọi với đối số thời gian chờ điểm nổi được đặt thành giá trị dương, khối trong nhiều nhất số giây được chỉ định bởi thời gian chờ và miễn là khóa không thể có được. Một đối số thời gian chờ của

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
39 chỉ định một sự chờ đợi không giới hạn. Nó bị cấm chỉ định thời gian chờ khi chặn là
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15.

Giá trị trả về là

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 nếu khóa được thu được thành công,
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15 nếu không (ví dụ: nếu thời gian chờ hết hạn).

Đã thay đổi trong phiên bản 3.2: Tham số thời gian chờ là mới.The timeout parameter is new.

phóng thích()¶()

Phát hành khóa, giảm mức đệ quy. Nếu sau khi giảm, nó bằng không, hãy đặt lại khóa để mở khóa (không thuộc sở hữu của bất kỳ luồng nào) và nếu bất kỳ luồng nào khác bị chặn chờ khóa được mở khóa, hãy cho phép chính xác một trong số chúng tiến hành. Nếu sau khi giảm mức đệ quy vẫn còn khác, thì khóa vẫn bị khóa và sở hữu bởi luồng gọi.

Chỉ gọi phương thức này khi luồng gọi sở hữu khóa. Một

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3 được nâng lên nếu phương thức này được gọi khi khóa được mở khóa.

Không có giá trị quay lại.

Đối tượng điều kiện lor

Một biến điều kiện luôn được liên kết với một số loại khóa; Điều này có thể được thông qua hoặc một sẽ được tạo theo mặc định. Vượt qua một trong là hữu ích khi một số biến điều kiện phải chia sẻ cùng một khóa. Khóa là một phần của đối tượng điều kiện: bạn không phải theo dõi nó một cách riêng biệt.

Một biến điều kiện tuân theo giao thức quản lý bối cảnh: Sử dụng câu lệnh

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
61 có được khóa liên quan trong suốt thời gian của khối kèm theo. Các phương thức
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 và
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 cũng gọi các phương thức tương ứng của khóa được liên kết.context management protocol: using the
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
61 statement acquires the associated lock for the duration of the enclosed block. The
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 and
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 methods also call the corresponding methods of the associated lock.

Các phương pháp khác phải được gọi với khóa liên kết được giữ. Phương thức

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 giải phóng khóa, và sau đó chặn cho đến khi một luồng khác đánh thức nó bằng cách gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 hoặc
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
66. Sau khi đánh thức,
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 lại mua lại khóa và trả lại. Cũng có thể chỉ định thời gian chờ.

Phương pháp

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 đánh thức một trong các luồng đang chờ biến điều kiện, nếu có đang chờ. Phương pháp
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
66 đánh thức tất cả các luồng chờ biến điều kiện.

Lưu ý: Các phương thức

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 và
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
66 don don phát hành khóa; Điều này có nghĩa là các luồng hoặc luồng được đánh thức sẽ không trở lại từ cuộc gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 của họ ngay lập tức, mà chỉ khi chủ đề gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 hoặc
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
66 cuối cùng đã từ bỏ quyền sở hữu khóa.

Kiểu lập trình điển hình sử dụng các biến điều kiện sử dụng khóa để đồng bộ hóa quyền truy cập vào một số trạng thái chung; Các chủ đề quan tâm đến một sự thay đổi cụ thể của cuộc gọi trạng thái

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 liên tục cho đến khi họ nhìn thấy trạng thái mong muốn, trong khi các luồng sửa đổi trạng thái gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 hoặc
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
66 khi chúng thay đổi trạng thái theo cách có thể là trạng thái mong muốn đối với một trong những người phục vụ bàn. Ví dụ, mã sau đây là tình huống người tiêu dùng nhà sản xuất chung với dung lượng bộ đệm không giới hạn:

# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()

Vòng lặp

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
78 Kiểm tra điều kiện ứng dụng là cần thiết vì
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 có thể quay lại sau một thời gian dài tùy ý và điều kiện khiến cuộc gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 có thể không còn đúng nữa. Điều này là vốn có của lập trình đa luồng. Phương pháp
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
81 có thể được sử dụng để tự động hóa việc kiểm tra điều kiện và giảm bớt tính toán thời gian chờ:

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()

Để lựa chọn giữa

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 và
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
66, hãy xem xét liệu một thay đổi trạng thái có thể thú vị đối với chỉ một hoặc một số luồng chờ hay không. Ví dụ. Trong một tình huống tiêu chuẩn nhà sản xuất điển hình, việc thêm một mặt hàng vào bộ đệm chỉ cần đánh thức một luồng người tiêu dùng.

Classthreading.Condition (Lock = none) ¶ threading.Condition(lock=None)

Lớp này thực hiện các đối tượng biến điều kiện. Một biến điều kiện cho phép một hoặc nhiều luồng chờ đợi cho đến khi chúng được thông báo bởi một luồng khác.

Nếu đối số khóa được đưa ra chứ không phải

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, thì đó phải là đối tượng
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
32 hoặc
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
52 và nó được sử dụng làm khóa bên dưới. Mặt khác, một đối tượng
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
52 mới được tạo và sử dụng làm khóa bên dưới.

Thay đổi trong phiên bản 3.3: Thay đổi từ chức năng nhà máy sang một lớp.changed from a factory function to a class.

có được (*args) ¶(*args)

Có được khóa cơ bản. Phương pháp này gọi phương thức tương ứng trên khóa bên dưới; Giá trị trả về là bất cứ điều gì phương thức đó trả về.

phóng thích()¶()

Phát hành khóa cơ bản. Phương pháp này gọi phương thức tương ứng trên khóa bên dưới; không có giá trị quay lại.

Đợi (thời gian chờ = Không) ¶(timeout=None)

Chờ cho đến khi được thông báo hoặc cho đến khi thời gian chờ xảy ra. Nếu luồng cuộc gọi không có được khóa khi phương thức này được gọi, một

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3 sẽ được nâng lên.

Phương pháp này phát hành khóa bên dưới, và sau đó chặn cho đến khi nó được đánh thức bởi một cuộc gọi

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 hoặc
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
66 cho cùng một biến điều kiện trong một luồng khác hoặc cho đến khi thời gian chờ tùy chọn xảy ra. Sau khi đánh thức hoặc hẹn giờ, nó lại mua lại khóa và trả lại.

Khi đối số thời gian chờ có mặt chứ không phải

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, nó sẽ là một số điểm nổi chỉ định thời gian chờ cho hoạt động tính bằng giây (hoặc phân số của chúng).

Khi khóa bên dưới là

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
52, nó không được phát hành bằng phương pháp
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 của nó, vì điều này có thể không thực sự mở khóa khóa khi nó được thu nhận nhiều lần. Thay vào đó, một giao diện nội bộ của lớp
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
52 được sử dụng, thực sự mở ra nó ngay cả khi nó đã được thu nhận một cách đệ quy nhiều lần. Một giao diện bên trong khác sau đó được sử dụng để khôi phục mức độ đệ quy khi khóa được phản ứng lại.

Giá trị trả về là

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 trừ khi hết thời gian chờ đã hết, trong trường hợp đó là
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15.

Đã thay đổi trong phiên bản 3.2: Trước đây, phương thức luôn được trả về

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3.Previously, the method always returned
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3.

Wait_for (vị từ, thời gian chờ = Không) ¶(predicate, timeout=None)

Đợi cho đến khi một điều kiện đánh giá là đúng. Vị từ phải là một cuộc gọi có thể gọi mà kết quả sẽ được hiểu là giá trị boolean. Một thời gian chờ có thể được cung cấp cho thời gian tối đa để chờ đợi.

Phương pháp tiện ích này có thể gọi

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 liên tục cho đến khi vị từ được thỏa mãn hoặc cho đến khi thời gian chờ xảy ra. Giá trị trả về là giá trị trả về cuối cùng của vị ngữ và sẽ đánh giá thành
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15 nếu phương thức hết thời gian.

Bỏ qua tính năng thời gian chờ, gọi phương thức này gần như tương đương với việc viết:

while not predicate():
    cv.wait()

Do đó, các quy tắc tương tự được áp dụng như với

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64: Khóa phải được giữ khi được gọi và được mua lại khi trả lại. Các vị ngữ được đánh giá với khóa giữ.

Mới trong phiên bản 3.2.

Thông báo (n = 1)(n=1)

Theo mặc định, đánh thức một chủ đề chờ đợi điều kiện này, nếu có. Nếu luồng cuộc gọi không có được khóa khi phương thức này được gọi, một

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3 sẽ được nâng lên.

Phương pháp này thức dậy nhiều nhất n của các luồng đang chờ biến điều kiện; Đó là một không có nếu không có chủ đề đang chờ đợi.

Việc triển khai hiện tại thức dậy chính xác n chủ đề, nếu ít nhất n chủ đề đang chờ. Tuy nhiên, nó không an toàn để dựa vào hành vi này. Một tương lai, việc thực hiện tối ưu hóa đôi khi có thể thức dậy nhiều hơn n chủ đề.

Lưu ý: Một luồng đánh thức không thực sự quay lại từ cuộc gọi

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 của nó cho đến khi nó có thể làm lại khóa. Vì
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65 không giải phóng khóa, nên người gọi của nó nên.

notify_all () ¶()

Thức dậy tất cả các chủ đề đang chờ đợi điều kiện này. Phương pháp này hoạt động như

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
65, nhưng đánh thức tất cả các luồng chờ thay vì một. Nếu luồng cuộc gọi không có được khóa khi phương thức này được gọi, một
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3 sẽ được nâng lên.

Phương pháp

mydata = threading.local()
mydata.x = 1
06 là bí danh không dùng nữa cho phương pháp này.

Đối tượng semaphore

Đây là một trong những nguyên thủy đồng bộ hóa lâu đời nhất trong lịch sử khoa học máy tính, được phát minh bởi nhà khoa học máy tính đầu tiên của Hà Lan Edsger W. Dijkstra (ông đã sử dụng tên

mydata = threading.local()
mydata.x = 1
07 và
mydata = threading.local()
mydata.x = 1
08 thay vì
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 và
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23).

Một semaphore quản lý một bộ đếm nội bộ bị giảm bởi mỗi cuộc gọi

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 và được tăng lên bởi mỗi cuộc gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23. Bộ đếm không bao giờ có thể xuống dưới 0; Khi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 thấy rằng nó bằng không, nó sẽ chặn, chờ cho đến khi một số luồng khác gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23.

Semaphores cũng hỗ trợ giao thức quản lý bối cảnh.context management protocol.

Classthreading.Semaphore (value = 1) ¶ threading.Semaphore(value=1)

Lớp này thực hiện các đối tượng Semaphore. Một semaphore quản lý một bộ đếm nguyên tử đại diện cho số lượng

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 gọi là trừ đi số lượng cuộc gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22, cộng với giá trị ban đầu. Phương pháp
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 chặn nếu cần thiết cho đến khi nó có thể quay lại mà không làm cho bộ đếm âm. Nếu không được đưa ra, giá trị mặc định là 1.

Đối số tùy chọn cho giá trị ban đầu cho bộ đếm nội bộ; Nó mặc định là

mydata = threading.local()
mydata.x = 1
18. Nếu giá trị được đưa ra là nhỏ hơn 0,
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
4 sẽ được nâng lên.

Thay đổi trong phiên bản 3.3: Thay đổi từ chức năng nhà máy sang một lớp.changed from a factory function to a class.

có được (chặn = true, thời gian chờ = none) ¶(blocking=True, timeout=None)

Có được một semaphore.

Khi được gọi mà không có tranh luận:

  • Nếu bộ đếm bên trong lớn hơn 0 khi nhập, hãy giảm một và trả về

    import threading
    import time
    
    
    class ThreadingExample(object):
        """ Threading example class
    
        The run() method will be started and it will run in the background
        until the application exits.
        """
    
        def __init__(self, interval=1):
            """ Constructor
    
            :type interval: int
            :param interval: Check interval, in seconds
            """
            self.interval = interval
    
            thread = threading.Thread(target=self.run, args=())
            thread.daemon = True                            # Daemonize thread
            thread.start()                                  # Start the execution
    
        def run(self):
            """ Method that runs forever """
            while True:
                # Do something
                print('Doing something imporant in the background')
    
                time.sleep(self.interval)
    
    example = ThreadingExample()
    time.sleep(3)
    print('Checkpoint')
    time.sleep(2)
    print('Bye')
    
    10 ngay lập tức.

  • Nếu bộ đếm bên trong bằng không trên mục nhập, hãy chặn cho đến khi đánh thức bằng một cuộc gọi đến

    import threading
    import time
    
    
    class ThreadingExample(object):
        """ Threading example class
    
        The run() method will be started and it will run in the background
        until the application exits.
        """
    
        def __init__(self, interval=1):
            """ Constructor
    
            :type interval: int
            :param interval: Check interval, in seconds
            """
            self.interval = interval
    
            thread = threading.Thread(target=self.run, args=())
            thread.daemon = True                            # Daemonize thread
            thread.start()                                  # Start the execution
    
        def run(self):
            """ Method that runs forever """
            while True:
                # Do something
                print('Doing something imporant in the background')
    
                time.sleep(self.interval)
    
    example = ThreadingExample()
    time.sleep(3)
    print('Checkpoint')
    time.sleep(2)
    print('Bye')
    
    23. Sau khi đánh thức (và bộ đếm lớn hơn 0), giảm bộ đếm xuống 1 và trả về
    import threading
    import time
    
    
    class ThreadingExample(object):
        """ Threading example class
    
        The run() method will be started and it will run in the background
        until the application exits.
        """
    
        def __init__(self, interval=1):
            """ Constructor
    
            :type interval: int
            :param interval: Check interval, in seconds
            """
            self.interval = interval
    
            thread = threading.Thread(target=self.run, args=())
            thread.daemon = True                            # Daemonize thread
            thread.start()                                  # Start the execution
    
        def run(self):
            """ Method that runs forever """
            while True:
                # Do something
                print('Doing something imporant in the background')
    
                time.sleep(self.interval)
    
    example = ThreadingExample()
    time.sleep(3)
    print('Checkpoint')
    time.sleep(2)
    print('Bye')
    
    10. Chính xác một chủ đề sẽ bị đánh thức bởi mỗi cuộc gọi đến
    import threading
    import time
    
    
    class ThreadingExample(object):
        """ Threading example class
    
        The run() method will be started and it will run in the background
        until the application exits.
        """
    
        def __init__(self, interval=1):
            """ Constructor
    
            :type interval: int
            :param interval: Check interval, in seconds
            """
            self.interval = interval
    
            thread = threading.Thread(target=self.run, args=())
            thread.daemon = True                            # Daemonize thread
            thread.start()                                  # Start the execution
    
        def run(self):
            """ Method that runs forever """
            while True:
                # Do something
                print('Doing something imporant in the background')
    
                time.sleep(self.interval)
    
    example = ThreadingExample()
    time.sleep(3)
    print('Checkpoint')
    time.sleep(2)
    print('Bye')
    
    23. Thứ tự mà các chủ đề bị đánh thức không nên dựa vào.

Khi được gọi bằng chặn được đặt thành

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15, không chặn. Nếu một cuộc gọi không có đối số sẽ chặn, hãy trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15 ngay lập tức; Nếu không, hãy làm điều tương tự như khi được gọi mà không có đối số và trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10.

Khi được gọi với một thời gian chờ khác với

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, nó sẽ chặn trong hầu hết các thời gian chờ. Nếu việc mua lại không hoàn thành thành công trong khoảng đó, hãy trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
15. Trả lại
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 khác.

Đã thay đổi trong phiên bản 3.2: Tham số thời gian chờ là mới.The timeout parameter is new.

giải phóng (n = 1)(n=1)

Phát hành một semaphore, tăng bộ đếm nội bộ của n. Khi nó bằng không khi nhập và các chủ đề khác đang chờ nó trở nên lớn hơn 0 một lần nữa, hãy đánh thức n của các luồng đó.

Đã thay đổi trong phiên bản 3.9: Đã thêm tham số N để phát hành nhiều luồng chờ cùng một lúc.Added the n parameter to release multiple waiting threads at once.

Classthreading.boundedSemaphore (value = 1) ¶ threading.BoundedSemaphore(value=1)

Lớp thực hiện các đối tượng semaphore bị ràng buộc. Một semaphore bị ràng buộc kiểm tra để đảm bảo giá trị hiện tại của nó không vượt quá giá trị ban đầu. Nếu có,

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
4 được nâng lên. Trong hầu hết các tình huống, Semaphores được sử dụng để bảo vệ các nguồn lực với năng lực hạn chế. Nếu semaphore được phát hành quá nhiều lần thì đó là một dấu hiệu của một lỗi. Nếu không được đưa ra, giá trị mặc định là 1.

Thay đổi trong phiên bản 3.3: Thay đổi từ chức năng nhà máy sang một lớp.changed from a factory function to a class.

mydata = threading.local() mydata.x = 1 31 Ví dụ En

Semaphores thường được sử dụng để bảo vệ các tài nguyên với công suất hạn chế, ví dụ, một máy chủ cơ sở dữ liệu. Trong mọi tình huống mà kích thước của tài nguyên được cố định, bạn nên sử dụng semaphore bị ràng buộc. Trước khi sinh sản bất kỳ luồng công nhân nào, chủ đề chính của bạn sẽ khởi tạo semaphore:

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)

Sau khi sinh ra, các luồng công nhân gọi các phương thức thu nhận và phát hành Semaphore khi chúng cần kết nối với máy chủ:

with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()

Việc sử dụng một semaphore bị ràng buộc làm giảm khả năng lỗi lập trình khiến semaphore được giải phóng nhiều hơn so với nó có được sẽ không bị phát hiện.

Đối tượng sự kiện

Đây là một trong những cơ chế đơn giản nhất để giao tiếp giữa các luồng: một luồng báo hiệu một sự kiện và các luồng khác chờ đợi nó.

Một đối tượng sự kiện quản lý một cờ bên trong có thể được đặt thành đúng với phương thức

mydata = threading.local()
mydata.x = 1
32 và đặt lại thành sai với phương thức
mydata = threading.local()
mydata.x = 1
33. Phương thức
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 chặn cho đến khi cờ là đúng.

Lớp họcthreading.Event

Lớp thực hiện các đối tượng sự kiện. Một sự kiện quản lý một lá cờ có thể được đặt thành TRUE với phương thức

mydata = threading.local()
mydata.x = 1
32 và đặt lại thành sai với phương pháp
mydata = threading.local()
mydata.x = 1
33. Phương thức
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 chặn cho đến khi cờ là đúng. Cờ ban đầu là sai.

Thay đổi trong phiên bản 3.3: Thay đổi từ chức năng nhà máy sang một lớp.changed from a factory function to a class.

is_set ()()

Trả về

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 khi và chỉ khi cờ bên trong là đúng.

Phương pháp

mydata = threading.local()
mydata.x = 1
39 là bí danh không dùng nữa cho phương pháp này.

bộ()¶()

Đặt cờ bên trong thành true. Tất cả các chủ đề đang chờ nó trở thành sự thật đều được đánh thức. Các luồng gọi

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 Một khi cờ là đúng sẽ không chặn được.

xa lạ()¶()

Đặt lại cờ bên trong thành sai. Sau đó, các luồng gọi

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 sẽ chặn cho đến khi
mydata = threading.local()
mydata.x = 1
32 được gọi để đặt cờ bên trong thành True một lần nữa.

Đợi (thời gian chờ = Không) ¶(timeout=None)

Chặn cho đến khi cờ bên trong là đúng. Nếu cờ bên trong đúng khi nhập, hãy quay lại ngay lập tức. Mặt khác, chặn cho đến khi một luồng khác gọi

mydata = threading.local()
mydata.x = 1
32 để đặt cờ thành true hoặc cho đến khi thời gian chờ tùy chọn xảy ra.

Khi đối số thời gian chờ có mặt chứ không phải

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3, nó sẽ là một số điểm nổi chỉ định thời gian chờ cho hoạt động tính bằng giây (hoặc phân số của chúng).

Phương thức này trả về

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 khi và chỉ khi cờ bên trong được đặt thành true, trước khi cuộc gọi chờ hoặc sau khi chờ đợi, do đó, nó sẽ luôn trả về
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 trừ khi hết thời gian chờ và hết thời gian hoạt động.

Đã thay đổi trong phiên bản 3.1: Trước đây, phương thức luôn được trả về

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3.Previously, the method always returned
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3.

Đối tượng hẹn giờ

Lớp này đại diện cho một hành động chỉ nên được chạy sau một khoảng thời gian nhất định đã trôi qua - một bộ đếm thời gian.

mydata = threading.local()
mydata.x = 1
48 là một lớp con của
mydata = threading.local()
mydata.x = 1
6 và như vậy cũng hoạt động như một ví dụ về việc tạo các luồng tùy chỉnh.

Bộ định thời được bắt đầu, như với các chủ đề, bằng cách gọi phương thức

while not predicate():
    cv.wait()
6 của chúng. Bộ hẹn giờ có thể được dừng (trước khi hành động của nó đã bắt đầu) bằng cách gọi phương thức
mydata = threading.local()
mydata.x = 1
51. Khoảng thời gian của bộ hẹn giờ sẽ đợi trước khi thực hiện hành động của nó có thể không giống hệt như khoảng thời gian được chỉ định bởi người dùng.

Ví dụ:

def hello():
    print("hello, world")

t = Timer(30.0, hello)
t.start()  # after 30 seconds, "hello, world" will be printed

Classthreading.Timer (khoảng thời gian, hàm, args = none, kwargs = none) ¶ threading.Timer(interval, function, args=None, kwargs=None)

Tạo một bộ đếm thời gian sẽ chạy chức năng với các đối số tranh luận và từ khóa đối số kwargs, sau khi khoảng giây đã trôi qua. Nếu Args là

>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3 (mặc định) thì một danh sách trống sẽ được sử dụng. Nếu kwargs là
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
3 (mặc định) thì sẽ sử dụng một dict trống.

Thay đổi trong phiên bản 3.3: Thay đổi từ chức năng nhà máy sang một lớp.changed from a factory function to a class.

sự hủy bỏ()¶()

Dừng bộ đếm thời gian và hủy bỏ việc thực hiện hành động hẹn giờ. Điều này sẽ chỉ hoạt động nếu bộ đếm thời gian vẫn đang trong giai đoạn chờ đợi.

Đối tượng rào cản

Mới trong phiên bản 3.2.

Lớp này cung cấp một nguyên thủy đồng bộ hóa đơn giản để sử dụng bởi một số lượng cố định các luồng cần phải đợi nhau. Mỗi luồng cố gắng vượt qua rào cản bằng cách gọi phương thức

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 và sẽ chặn cho đến khi tất cả các luồng đã thực hiện các cuộc gọi
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 của họ. Tại thời điểm này, các chủ đề được phát hành đồng thời.

Rào cản có thể được sử dụng lại bất kỳ số lần cho cùng một số lượng chủ đề.

Ví dụ, đây là một cách đơn giản để đồng bộ hóa luồng máy khách và máy chủ:

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
0

Classthreading.Barrier (Parties, Action = none, Timeout = none) ¶threading.Barrier(parties, action=None, timeout=None)

Tạo một đối tượng rào cản cho các bên số lượng chủ đề. Một hành động, khi được cung cấp, là một cuộc gọi được gọi để được gọi bởi một trong các chủ đề khi chúng được phát hành. Thời gian chờ là giá trị thời gian chờ mặc định nếu không có gì được chỉ định cho phương thức

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64.

Đợi (thời gian chờ = Không) ¶(timeout=None)

Vượt qua rào cản. Khi tất cả các chủ đề tham gia hàng rào đã gọi là chức năng này, tất cả chúng đều được phát hành đồng thời. Nếu một thời gian chờ được cung cấp, nó được sử dụng theo sở thích cho bất kỳ thứ gì được cung cấp cho hàm tạo lớp.

Giá trị trả về là một số nguyên trong phạm vi 0 đến các bên - 1, khác nhau cho mỗi luồng. Điều này có thể được sử dụng để chọn một chủ đề để thực hiện một số công việc dọn phòng đặc biệt, ví dụ:

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
1

Nếu một hành động được cung cấp cho hàm tạo, một trong các luồng sẽ gọi nó trước khi được phát hành. Nếu cuộc gọi này gây ra lỗi, rào cản được đưa vào trạng thái bị hỏng.

Nếu cuộc gọi hết thời gian, rào cản được đưa vào trạng thái bị hỏng.

Phương pháp này có thể tăng ngoại lệ

mydata = threading.local()
mydata.x = 1
57 nếu rào cản bị hỏng hoặc đặt lại trong khi một luồng đang chờ.

cài lại()¶()

Trả hàng rào cho trạng thái mặc định, trống. Bất kỳ chủ đề đang chờ đợi trên nó sẽ nhận được ngoại lệ

mydata = threading.local()
mydata.x = 1
57.

Lưu ý rằng sử dụng chức năng này có thể yêu cầu một số đồng bộ hóa bên ngoài nếu có các luồng khác mà trạng thái không rõ. Nếu một rào cản bị phá vỡ, có thể tốt hơn là chỉ để nó và tạo ra một cái mới.

Huỷ bỏ()¶()

Đặt rào cản vào một trạng thái bị hỏng. Điều này khiến mọi cuộc gọi hoạt động hoặc trong tương lai đến

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
64 không thành công với
mydata = threading.local()
mydata.x = 1
57. Sử dụng điều này ví dụ nếu một trong các chủ đề cần hủy bỏ, để tránh giảm ứng dụng.

Có thể tốt hơn là chỉ cần tạo ra hàng rào với giá trị thời gian chờ hợp lý để tự động bảo vệ chống lại một trong các luồng sẽ bị đánh giá cao.

các bữa tiệc

Số lượng chủ đề cần thiết để vượt qua hàng rào.

n_waiting¶

Số lượng chủ đề hiện đang chờ đợi trong rào cản.

bị hỏng¶

Một boolean là

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
10 nếu rào cản ở trạng thái bị hỏng.

Ngoại lệ.BrokenBarrierRoror¶threading.BrokenBarrierError

Ngoại lệ này, một lớp con của

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
3, được nâng lên khi đối tượng
mydata = threading.local()
mydata.x = 1
63 được đặt lại hoặc bị hỏng.

Sử dụng khóa, điều kiện và semaphores trong câu lệnh import threading import time class ThreadingExample(object): """ Threading example class The run() method will be started and it will run in the background until the application exits. """ def __init__(self, interval=1): """ Constructor :type interval: int :param interval: Check interval, in seconds """ self.interval = interval thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): """ Method that runs forever """ while True: # Do something print('Doing something imporant in the background') time.sleep(self.interval) example = ThreadingExample() time.sleep(3) print('Checkpoint') time.sleep(2) print('Bye') 61

Tất cả các đối tượng được cung cấp bởi mô -đun này có các phương thức

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 và
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 có thể được sử dụng làm Trình quản lý ngữ cảnh cho câu lệnh
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
61. Phương thức
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
22 sẽ được gọi khi khối được nhập và
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
23 sẽ được gọi khi khối được thoát. Do đó, đoạn trích sau:

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
2

tương đương với:

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
3

Hiện tại,

import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
32,
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
52,
mydata = threading.local()
mydata.x = 1
72,
mydata = threading.local()
mydata.x = 1
31 và
mydata = threading.local()
mydata.x = 1
74 Các đối tượng có thể được sử dụng làm Trình quản lý bối cảnh câu lệnh
import threading
import time


class ThreadingExample(object):
    """ Threading example class

    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor

        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
61.

Các phương pháp của lớp chủ đề trong Python là gì?

Lớp luồng đại diện cho một hoạt động được chạy trong một luồng điều khiển riêng biệt. Có hai cách để chỉ định hoạt động: bằng cách chuyển một đối tượng có thể gọi cho hàm tạo hoặc bằng cách ghi đè phương thức Run () trong một lớp con. Không có phương thức nào khác (ngoại trừ hàm tạo) nên được ghi đè trong một lớp con.by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass.

Làm thế nào để bạn gọi một lớp bằng cách sử dụng chủ đề trong Python?

Chức năng và hàm tạo trong lớp luồng..
Trình xây dựng lớp chủ đề. Sau đây là cú pháp cơ bản của hàm tạo lớp luồng: Thread (nhóm = none, target = none, name = none, args = (), kwargs = {}) ....
bắt đầu () phương thức. Phương pháp này được sử dụng để bắt đầu hoạt động của luồng. ....
chạy () phương thức. Phương pháp đại diện cho hoạt động của luồng ..

Làm thế nào để bạn chạy một lớp chủ đề?

Phương thức Run () Phương thức Run () Phương thức của lớp luồng được gọi nếu luồng được xây dựng bằng một đối tượng có thể chạy riêng biệt nếu không phương thức này không làm gì và trả về.Khi phương thức Run () gọi, mã được chỉ định trong phương thức Run () được thực thi.Bạn có thể gọi phương thức Run () nhiều lần.The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.

Làm thế nào để bạn luồn một lớp con?

Làm thế nào để sử dụng một chủ đề trong một lớp con..
Xác định một lớp con mới của lớp chủ đề ..
Ghi đè phương thức _init __ (self [, args]) để thêm các đối số bổ sung ..
Sau đó, bạn cần ghi đè phương thức chạy (tự [, args]) để thực hiện những gì chủ đề nên làm khi nó được bắt đầu ..