Hướng dẫn can a thread spawn another thread python? - một chuỗi có thể sinh ra một chuỗi trăn khác không?

Tôi đang sử dụng Vanilla Python 2.7 được tải bằng Cygwin

Show

Tôi muốn có thể sinh ra một lớp con luồng gọi hàm cấp cao nhất và hàm cấp cao nhất sinh ra các luồng riêng biệt gọi các hàm cấp phụ. Đây là mã giả

import threading

#!/usr/bin/python
import threading

class Server(threading.Thread):
    def __init__(self, threadID, target):
        self.__threadID = threadID
        self.__target = target
        threading.Thread.__init__(self)

    # Function called when the thread's start() function is called
    def run(self):
        self.target()
        pass

    # This is the top level function called by other objects
    def reboot(self):
        # I want this function to spawn two threads
        # - First thread calls the __powerDown() function
        # - Secod thread calls the __powerUp() function, and pends
        #   until __powerDown() thread finishes
        pass

    def __powerDown(self):
        # What to put here?
        pass

    def __powerUp(self):
        # What to put here?
        pass

    __threadID = ''
    __target = None


# Code calling above code
server = Server(123, reboot) # Will this work?

Hỏi ngày 24 tháng 9 năm 2013 lúc 18:39Sep 24, 2013 at 18:39

Hướng dẫn can a thread spawn another thread python? - một chuỗi có thể sinh ra một chuỗi trăn khác không?

Chris Fchris fChris F

12.2K25 Huy hiệu vàng82 Huy hiệu bạc165 Huy hiệu Đồng25 gold badges82 silver badges165 bronze badges

1

Một cái gì đó như thế này?

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down

Đã trả lời ngày 24 tháng 9 năm 2013 lúc 19:02Sep 24, 2013 at 19:02

FreakishFreakishfreakish

52.7K8 Huy hiệu vàng128 Huy hiệu bạc165 Huy hiệu Đồng8 gold badges128 silver badges165 bronze badges

1

Có rất nhiều cách để làm điều này, tôi quen thuộc nhất với ThreadPools và chúng có giao diện rất dễ dàng để gọi các luồng và tham gia cùng chúng ...

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass

Nó hơi khác so với cách bạn đã nói, bởi vì trước tiên tôi gọi Powerdown, hãy chờ điều đó kết thúc, và sau đó gọi Powerup, nhưng tôi nghĩ rằng nó đã được thực hiện.

Đã trả lời ngày 24 tháng 9 năm 2013 lúc 18:47Sep 24, 2013 at 18:47

Hướng dẫn can a thread spawn another thread python? - một chuỗi có thể sinh ra một chuỗi trăn khác không?

Cameron Sparrcameron SparrCameron Sparr

3,8202 huy hiệu vàng21 Huy hiệu bạc31 Huy hiệu đồng2 gold badges21 silver badges31 bronze badges

3

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để làm sâu sắc thêm sự hiểu biết của bạn: Xây dựng bằng Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Threading in Python

Chủ đề có thể sinh ra chủ đề Python không?

Chủ đề trong Python. Một luồng là một chuỗi các hướng dẫn đang được thực thi trong bối cảnh của một quá trình. Một quy trình có thể sinh ra nhiều luồng nhưng tất cả chúng sẽ chia sẻ cùng một bộ nhớ.

  • Một chủ đề có thể sinh ra một chủ đề khác không?
  • Đúng. Tuy nhiên, vấn đề điển hình là công việc/chủ đề không bị hạn chế. Sử dụng phương pháp bạn đã phác thảo, thật dễ dàng để sinh ra nhiều luồng và có số lượng chủ đề cao phi logic cho công việc phải được thực hiện trên một số lượng lõi hạn chế.
  • Hai luồng có thể gọi cùng một hàm python không?
  • Một luồng có thể thực thi một hàm song song với các luồng khác. Mỗi luồng chia sẻ cùng một mã, dữ liệu và tệp trong khi chúng có ngăn xếp và thanh ghi riêng của họ.
  • Có bao nhiêu chủ đề có thể được sinh ra python?

Mỗi lõi CPU có thể có tối đa hai luồng nếu CPU của bạn có kích hoạt đa/siêu luồng. Bạn có thể tìm kiếm bộ xử lý CPU của riêng bạn để tìm hiểu thêm. Đối với người dùng Mac, bạn có thể tìm hiểu từ Giới thiệu> Báo cáo hệ thống.

Python Threading cho phép bạn có các phần khác nhau trong chương trình chạy đồng thời và có thể đơn giản hóa thiết kế của bạn. Nếu bạn đã có một số kinh nghiệm về Python và muốn tăng tốc chương trình của mình bằng cách sử dụng các chủ đề, thì hướng dẫn này là dành cho bạn!

Trong bài viết này, bạn sẽ học:

Chủ đề là gì

Cách tạo chủ đề và chờ chúng hoàn thành

Cách sử dụng

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
7

Làm thế nào để tránh điều kiện cuộc đua

Cách sử dụng các công cụ phổ biến mà Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8 cung cấp

Bài viết này giả định rằng bạn đã có những điều cơ bản của Python và bạn sử dụng ít nhất phiên bản 3.6 để chạy các ví dụ. Nếu bạn cần bồi dưỡng, bạn có thể bắt đầu với các đường dẫn học tập Python và tăng tốc.

Nếu bạn không chắc chắn nếu bạn muốn sử dụng Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8,
x = threading.Thread(target=thread_function, args=(1,))
x.start()
0 hoặc
x = threading.Thread(target=thread_function, args=(1,))
x.start()
1, thì bạn có thể kiểm tra tăng tốc chương trình Python của mình với sự đồng thời.

Tất cả các nguồn được sử dụng trong hướng dẫn này đều có sẵn cho bạn trong repo Python GitHub thực sự.

Kiến trúc chương trình của bạn để sử dụng luồng cũng có thể cung cấp lợi ích trong thiết kế rõ ràng. Hầu hết các ví dụ mà bạn sẽ tìm hiểu trong hướng dẫn này không nhất thiết sẽ chạy nhanh hơn vì chúng sử dụng các chủ đề. Sử dụng luồng trong chúng giúp làm cho thiết kế sạch hơn và dễ lý luận hơn.

Vì vậy, hãy để Lôi ngừng nói về việc xâu chuỗi và bắt đầu sử dụng nó!

Bắt đầu một chủ đề

Bây giờ, bạn đã có một ý tưởng về một chủ đề là gì, hãy để học cách tạo ra một chủ đề. Thư viện tiêu chuẩn Python cung cấp

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8, trong đó chứa hầu hết các nguyên thủy mà bạn sẽ thấy trong bài viết này.
x = threading.Thread(target=thread_function, args=(1,))
x.start()
5, trong mô -đun này, đóng gói độc đáo các chủ đề, cung cấp một giao diện sạch để làm việc với chúng.

Để bắt đầu một luồng riêng biệt, bạn tạo một thể hiện

x = threading.Thread(target=thread_function, args=(1,))
x.start()
5 và sau đó nói với
x = threading.Thread(target=thread_function, args=(1,))
x.start()
7:

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")

Nếu bạn nhìn xung quanh các câu lệnh ghi nhật ký, bạn có thể thấy rằng phần

x = threading.Thread(target=thread_function, args=(1,))
x.start()
8 đang tạo và bắt đầu chủ đề:

x = threading.Thread(target=thread_function, args=(1,))
x.start()

Khi bạn tạo

x = threading.Thread(target=thread_function, args=(1,))
x.start()
5, bạn chuyển nó một hàm và một danh sách chứa các đối số cho hàm đó. Trong trường hợp này, bạn đã nói với
x = threading.Thread(target=thread_function, args=(1,))
x.start()
5 chạy
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
1 và vượt qua nó
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
2 như một cuộc tranh luận.

Đối với bài viết này, bạn sẽ sử dụng các số nguyên tuần tự làm tên cho các chủ đề của bạn. Có

$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
3, trả về một tên duy nhất cho mỗi luồng, nhưng chúng thường không ngắn cũng không dễ đọc.

$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
1 bản thân nó không làm nhiều. Nó chỉ đơn giản là ghi lại một số tin nhắn với
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
5 ở giữa chúng.

Khi bạn chạy chương trình này như hiện tại (với dòng hai mươi nhận xét), đầu ra sẽ trông như thế này:

$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing

Bạn sẽ nhận thấy rằng

x = threading.Thread(target=thread_function, args=(1,))
x.start()
5 đã hoàn thành sau phần
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
7 trong mã của bạn đã làm. Bạn sẽ quay lại lý do tại sao và nói về dòng bí ẩn hai mươi trong phần tiếp theo.

Chủ đề daemon

Trong khoa học máy tính,

$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
8 là một quá trình chạy trong nền.

Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8 có ý nghĩa cụ thể hơn cho
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
8. Một luồng
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
8 sẽ tắt ngay lập tức khi chương trình thoát ra. Một cách để suy nghĩ về các định nghĩa này là xem xét chuỗi
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
8 Một luồng chạy trong nền mà không phải lo lắng về việc tắt nó xuống.

Nếu một chương trình đang chạy

x = threading.Thread(target=thread_function, args=(1,), daemon=True)
3 không phải là
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
4, thì chương trình sẽ đợi các luồng đó hoàn thành trước khi kết thúc.
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
3 đó là daemon, tuy nhiên, chỉ bị giết bất cứ nơi nào khi họ đang xuất hiện.

Hãy cùng xem xét kỹ hơn một chút về đầu ra của chương trình của bạn ở trên. Hai dòng cuối cùng là bit thú vị. Khi bạn chạy chương trình, bạn sẽ nhận thấy rằng có một khoảng dừng (khoảng 2 giây) sau khi

x = threading.Thread(target=thread_function, args=(1,), daemon=True)
6 đã in tin nhắn
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
7 của nó và trước khi chủ đề kết thúc.

Tạm dừng này là Python chờ đợi chủ đề không hoàn thành. Khi chương trình Python của bạn kết thúc, một phần của quá trình tắt máy là làm sạch thói quen luồng.

Nếu bạn nhìn vào nguồn cho Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8, bạn sẽ thấy rằng
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
9 đi qua tất cả các luồng đang chạy và gọi
$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
0 trên mỗi cái không có đặt cờ
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
8.

Vì vậy, chương trình của bạn chờ đợi để thoát vì chính chủ đề đang chờ trong một giấc ngủ. Ngay sau khi hoàn thành và in tin nhắn,

$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
0 sẽ trở lại và chương trình có thể thoát.

Thông thường, hành vi này là những gì bạn muốn, nhưng có những tùy chọn khác có sẵn cho chúng tôi. Trước tiên, hãy lặp lại chương trình với chủ đề

$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
8. Bạn làm điều đó bằng cách thay đổi cách bạn xây dựng
x = threading.Thread(target=thread_function, args=(1,))
x.start()
5, thêm cờ
$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
5:

x = threading.Thread(target=thread_function, args=(1,), daemon=True)

Khi bạn chạy chương trình ngay bây giờ, bạn sẽ thấy đầu ra này:

$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done

Sự khác biệt ở đây là dòng cuối cùng của đầu ra bị thiếu.

$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
1 không có cơ hội hoàn thành. Đó là một chủ đề
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
8, vì vậy khi
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
6 đi đến cuối mã của nó và chương trình muốn hoàn thành, daemon đã bị giết.

$ ./daemon_thread.py Main : before creating thread Main : before running thread Thread 1: starting Main : wait for the thread to finish Main : all done 9 Một chủ đề

Chủ đề daemon rất tiện dụng, nhưng khi nào bạn muốn đợi một chủ đề dừng lại? Thế còn khi bạn muốn làm điều đó và không thoát khỏi chương trình của bạn? Bây giờ, hãy để Lừa quay trở lại chương trình ban đầu của bạn và xem xét điều đó đã nhận xét về dòng hai mươi:

Để nói với một chủ đề để đợi một chủ đề khác kết thúc, bạn gọi

$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
0. Nếu bạn giải quyết dòng đó, luồng chính sẽ tạm dừng và chờ luồng
import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)
1 hoàn thành chạy.

Bạn đã kiểm tra điều này trên mã với luồng daemon hoặc luồng thông thường? Hóa ra nó không quan trọng. Nếu bạn

$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
0 một chủ đề, câu lệnh đó sẽ đợi cho đến khi một loại luồng được hoàn thành.

Làm việc với nhiều chủ đề

Mã ví dụ cho đến nay chỉ hoạt động với hai luồng: luồng chính và một luồng bạn bắt đầu với đối tượng

import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)
3.

Thông thường, bạn sẽ muốn bắt đầu một số chủ đề và yêu cầu chúng làm công việc thú vị. Hãy bắt đầu bằng cách nhìn vào cách làm điều đó khó hơn, và sau đó bạn sẽ chuyển sang một phương pháp dễ dàng hơn.

Cách khó hơn để bắt đầu nhiều luồng là cách mà bạn đã biết:

import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)

Mã này sử dụng cùng một cơ chế mà bạn đã thấy ở trên để bắt đầu một luồng, tạo một đối tượng

x = threading.Thread(target=thread_function, args=(1,))
x.start()
5 và sau đó gọi
x = threading.Thread(target=thread_function, args=(1,))
x.start()
7. Chương trình giữ một danh sách các đối tượng
x = threading.Thread(target=thread_function, args=(1,))
x.start()
5 để sau đó có thể đợi chúng sau đó bằng cách sử dụng
$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
0.

Chạy mã này nhiều lần có thể sẽ tạo ra một số kết quả thú vị. Ở đây, một ví dụ đầu ra từ máy của tôi:

$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done

Nếu bạn đi qua đầu ra một cách cẩn thận, bạn sẽ thấy cả ba chủ đề bắt đầu theo thứ tự bạn có thể mong đợi, nhưng trong trường hợp này, chúng kết thúc theo thứ tự ngược lại! Nhiều lần chạy sẽ tạo ra các thứ tự khác nhau. Tìm tin nhắn

import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)
8 để cho bạn biết khi mỗi chủ đề hoàn thành.

Thứ tự mà các luồng được chạy được xác định bởi hệ điều hành và có thể khá khó dự đoán. Nó có thể (và có thể sẽ) thay đổi từ chạy đến chạy, vì vậy bạn cần nhận thức được điều đó khi bạn thiết kế các thuật toán sử dụng luồng.

May mắn thay, Python cung cấp cho bạn một số nguyên thủy mà bạn sẽ xem xét sau này để giúp phối hợp các luồng và khiến chúng chạy cùng nhau. Trước đó, hãy để Lôi nhìn vào cách làm cho việc quản lý một nhóm các chủ đề dễ dàng hơn một chút.

Sử dụng 1import logging 2import threading 3import time 4 5def thread_function(name): 6 logging.info("Thread %s: starting", name) 7 time.sleep(2) 8 logging.info("Thread %s: finishing", name) 9 10if __name__ == "__main__": 11 format = "%(asctime)s: %(message)s" 12 logging.basicConfig(format=format, level=logging.INFO, 13 datefmt="%H:%M:%S") 14 15 logging.info("Main : before creating thread") 16 x = threading.Thread(target=thread_function, args=(1,)) 17 logging.info("Main : before running thread") 18 x.start() 19 logging.info("Main : wait for the thread to finish") 20 # x.join() 21 logging.info("Main : all done") 7

Có một cách dễ dàng hơn để bắt đầu một nhóm các chủ đề so với cái bạn thấy ở trên. Nó được gọi là

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
7, và nó là một phần của thư viện tiêu chuẩn trong
$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done
1 (kể từ Python 3.2).

Cách dễ nhất để tạo nó là một người quản lý bối cảnh, sử dụng tuyên bố

$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done
2 để quản lý việc tạo và phá hủy nhóm.

Tại đây,

x = threading.Thread(target=thread_function, args=(1,), daemon=True)
6 từ ví dụ cuối cùng được viết lại để sử dụng
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
7:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
0

Mã tạo ra

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
7 như một người quản lý bối cảnh, cho biết nó có bao nhiêu chủ đề công nhân muốn trong nhóm. Sau đó, nó sử dụng
$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done
6 để bước qua một số thứ khác, trong trường hợp của bạn
$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done
7, chuyển từng cái một luồng trong nhóm.

Phần cuối của khối

$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done
2 khiến
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
7 thực hiện
$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
0 trên mỗi luồng trong nhóm. Chúng tôi khuyên bạn nên sử dụng
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
7 như một trình quản lý ngữ cảnh khi bạn có thể để bạn không bao giờ quên
$ ./daemon_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
0 các chủ đề.

Chạy mã ví dụ đã sửa của bạn sẽ tạo ra đầu ra trông như thế này:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
1

Một lần nữa, hãy chú ý cách

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 kết thúc trước
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
04. Việc lập lịch trình của các chủ đề được thực hiện bởi hệ điều hành và không tuân theo một kế hoạch mà dễ dàng tìm ra.

Điều kiện chủng tộc

Trước khi bạn chuyển sang một số tính năng khác được giấu trong Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8, hãy để nói chuyện một chút về một trong những vấn đề khó khăn hơn mà bạn sẽ gặp phải khi viết các chương trình được thực hiện: điều kiện cuộc đua.

Khi bạn đã thấy một điều kiện cuộc đua là gì và nhìn vào một người xảy ra, bạn sẽ chuyển sang một số nguyên thủy được cung cấp bởi thư viện tiêu chuẩn để ngăn chặn các điều kiện chủng tộc xảy ra.

Điều kiện cuộc đua có thể xảy ra khi hai hoặc nhiều luồng truy cập một phần dữ liệu hoặc tài nguyên được chia sẻ. Trong ví dụ này, bạn sẽ tạo ra một điều kiện cuộc đua lớn xảy ra mọi lúc, nhưng lưu ý rằng hầu hết các điều kiện chủng tộc không rõ ràng như vậy. Thông thường, chúng chỉ xảy ra hiếm khi và chúng có thể tạo ra kết quả khó hiểu. Như bạn có thể tưởng tượng, điều này làm cho chúng khá khó để gỡ lỗi.

May mắn thay, điều kiện cuộc đua này sẽ xảy ra mỗi lần và bạn sẽ đi qua nó một cách chi tiết để giải thích những gì đang xảy ra.

Trong ví dụ này, bạn sẽ viết một lớp cập nhật cơ sở dữ liệu. Được rồi, bạn không thực sự sẽ có một cơ sở dữ liệu: bạn sẽ chỉ giả mạo nó, bởi vì đó không phải là điểm của bài viết này.

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
06 của bạn sẽ có các phương pháp
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
07 và
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
2

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
06 đang theo dõi một số duy nhất:
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
10. Đây sẽ là dữ liệu được chia sẻ mà bạn sẽ thấy điều kiện cuộc đua.

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
07 Đơn giản chỉ cần khởi tạo
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
10 đến 0. Càng xa càng tốt.

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08 trông hơi lạ. Nó mô phỏng việc đọc một giá trị từ cơ sở dữ liệu, thực hiện một số tính toán trên nó và sau đó viết một giá trị mới trở lại cơ sở dữ liệu.

Trong trường hợp này, đọc từ cơ sở dữ liệu chỉ có nghĩa là sao chép

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
10 sang biến cục bộ. Việc tính toán chỉ là để thêm một vào giá trị và sau đó
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
15 cho một chút. Cuối cùng, nó ghi lại giá trị bằng cách sao chép giá trị cục bộ trở lại
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
10.

Đây là cách bạn sử dụng

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
06 này:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
3

Chương trình tạo ra một

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
7 với hai luồng và sau đó gọi
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
19 trên mỗi người trong số họ, bảo họ chạy
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
20.

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
19 có chữ ký cho phép cả đối số vị trí và được đặt tên được chuyển đến hàm chạy trong luồng:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
4

Trong việc sử dụng ở trên,

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
22 được thông qua như là đối số vị trí đầu tiên và duy nhất cho
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
20. Bạn sẽ thấy sau trong bài viết này, nơi bạn có thể vượt qua nhiều đối số theo cách tương tự.

Vì mỗi luồng chạy

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08 và
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08 thêm một vào
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
10, bạn có thể mong đợi
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
27 là
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
28 khi nó được in ra ở cuối. Nhưng bạn sẽ không xem xét ví dụ này nếu đó là trường hợp. Nếu bạn chạy mã trên, đầu ra trông như thế này:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
5

Bạn có thể đã mong đợi điều đó sẽ xảy ra, nhưng hãy để Lôi nhìn vào các chi tiết về những gì mà thực sự đang diễn ra ở đây, vì điều đó sẽ làm cho giải pháp cho vấn đề này dễ hiểu hơn.

Một chủ đề

Trước khi bạn đi sâu vào vấn đề này với hai chủ đề, hãy để Lùi lại và nói một chút về một số chi tiết về cách các chủ đề hoạt động.

Bạn đã giành chiến thắng khi đi sâu vào tất cả các chi tiết ở đây, vì điều đó không quan trọng ở cấp độ này. Chúng tôi cũng sẽ đơn giản hóa một vài điều theo cách mà giành được chính xác về mặt kỹ thuật nhưng sẽ cho bạn ý tưởng đúng về những gì đang xảy ra.

Khi bạn nói với

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
7 của mình để chạy từng luồng, bạn sẽ cho nó biết chức năng nào sẽ chạy và những tham số nào sẽ truyền cho nó:
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
30.

Kết quả của điều này là mỗi luồng trong nhóm sẽ gọi

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
31. Lưu ý rằng
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
32 là một tham chiếu đến đối tượng
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
06 được tạo trong
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
6. Gọi
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08 trên đối tượng đó gọi một phương thức thể hiện trên đối tượng đó.

Mỗi luồng sẽ có một tham chiếu đến cùng một đối tượng

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
06,
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
32. Mỗi luồng cũng sẽ có một giá trị duy nhất,
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
22, để làm cho các câu lệnh ghi nhật ký dễ đọc hơn một chút:

Hướng dẫn can a thread spawn another thread python? - một chuỗi có thể sinh ra một chuỗi trăn khác không?

Khi luồng bắt đầu chạy

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08, nó có phiên bản riêng của tất cả dữ liệu cục bộ cho chức năng. Trong trường hợp của
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08, đây là
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41. Đây chắc chắn là một điều tốt. Nếu không, hai luồng chạy cùng một chức năng sẽ luôn gây nhầm lẫn cho nhau. Nó có nghĩa là tất cả các biến được phạm vi (hoặc cục bộ) đến một hàm đều an toàn.local to the function. In the case of
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08, this is
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41. This is definitely a good thing. Otherwise, two threads running the same function would always confuse each other. It means that all variables that are scoped (or local) to a function are thread-safe.

Bây giờ bạn có thể bắt đầu đi qua những gì xảy ra nếu bạn chạy chương trình ở trên với một luồng duy nhất và một cuộc gọi đến

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08.

Hình ảnh bên dưới bước thông qua việc thực hiện

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08 nếu chỉ chạy một luồng. Câu lệnh được hiển thị ở bên trái theo sau là sơ đồ hiển thị các giá trị trong luồng
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41 và được chia sẻ
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
27:

Hướng dẫn can a thread spawn another thread python? - một chuỗi có thể sinh ra một chuỗi trăn khác không?

Sơ đồ được đặt ra để thời gian tăng khi bạn di chuyển từ trên xuống dưới. Nó bắt đầu khi

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 được tạo và kết thúc khi nó bị chấm dứt.

Khi

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 bắt đầu,
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
48 bằng không. Dòng mã đầu tiên trong phương thức,
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
49, sao chép giá trị 0 vào biến cục bộ. Tiếp theo, nó tăng giá trị của
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41 với câu lệnh
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
51. Bạn có thể thấy
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
10 trong
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 được đặt thành một.

Tiếp theo

$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
5 được gọi, làm cho tạm dừng luồng hiện tại và cho phép các luồng khác chạy. Vì chỉ có một chủ đề trong ví dụ này, điều này không có hiệu lực.

Khi

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 thức dậy và tiếp tục, nó sao chép giá trị mới từ
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41 đến
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
48, và sau đó luồng hoàn tất. Bạn có thể thấy rằng
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
27 được đặt thành một.

Càng xa càng tốt. Bạn đã chạy

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08 một lần và
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
48 đã được tăng lên một.

Hai chủ đề

Quay trở lại điều kiện cuộc đua, hai luồng sẽ chạy đồng thời nhưng không cùng một lúc. Mỗi người sẽ có phiên bản riêng của họ là

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41 và mỗi người sẽ chỉ ra cùng một
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
32. Chính đối tượng
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
32 được chia sẻ này sẽ gây ra các vấn đề.

Chương trình bắt đầu với

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 đang chạy
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08:

Hướng dẫn can a thread spawn another thread python? - một chuỗi có thể sinh ra một chuỗi trăn khác không?

Khi

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 gọi
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
5, nó cho phép luồng khác bắt đầu chạy. Đây là nơi mà mọi thứ trở nên thú vị.

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
68 bắt đầu và thực hiện các hoạt động tương tự. Nó cũng sao chép
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
27 vào riêng tư
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41 và điều này được chia sẻ
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
27 vẫn chưa được cập nhật:

Hướng dẫn can a thread spawn another thread python? - một chuỗi có thể sinh ra một chuỗi trăn khác không?

Khi

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
68 cuối cùng đi ngủ,
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
27 được chia sẻ vẫn chưa được sửa đổi ở mức 0 và cả hai phiên bản riêng của
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41 đều có giá trị một.

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 hiện thức dậy và lưu phiên bản
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41 và sau đó chấm dứt, cho
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
68 cơ hội cuối cùng để chạy.
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
68 không biết rằng
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 đã chạy và cập nhật
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
27 trong khi nó đang ngủ. Nó lưu trữ phiên bản
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
41 của nó vào
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
27, cũng đặt nó thành một:

Hướng dẫn can a thread spawn another thread python? - một chuỗi có thể sinh ra một chuỗi trăn khác không?

Hai luồng có quyền truy cập xen kẽ vào một đối tượng được chia sẻ duy nhất, ghi đè lên kết quả của nhau. Các điều kiện cuộc đua tương tự có thể phát sinh khi một luồng giải phóng bộ nhớ hoặc đóng tay cầm tệp trước khi luồng khác được truy cập xong.

Tại sao đây là một ví dụ ngớ ngẩn

Ví dụ trên được tạo ra để đảm bảo rằng điều kiện cuộc đua xảy ra mỗi khi bạn chạy chương trình của mình. Vì hệ điều hành có thể trao đổi một luồng bất cứ lúc nào, nên có thể làm gián đoạn một câu lệnh như

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
83 sau khi nó đã đọc giá trị của
import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)
1 nhưng trước khi nó viết lại giá trị tăng.

Các chi tiết về cách điều này xảy ra khá thú vị, nhưng không cần thiết cho phần còn lại của bài viết này, vì vậy hãy thoải mái bỏ qua phần ẩn này.

Mã trên không phải là ngoài đó như bạn có thể nghĩ ban đầu. Nó được thiết kế để buộc một điều kiện chủng tộc mỗi khi bạn chạy nó, nhưng điều đó giúp giải quyết dễ dàng hơn nhiều so với hầu hết các điều kiện chủng tộc.

Có hai điều cần ghi nhớ khi nghĩ về điều kiện chủng tộc:

  1. Ngay cả một hoạt động như

    import threading
    
    class Server(threading.Thread):
        # some code
    
        # This is the top level function called by other objects
        def reboot(self):
            # perhaps add a lock
            if not hasattr(self, "_down"):
                self._down = threading.Thread(target=self.__powerDown)
                self._down.start()
                up = threading.Thread(target=self.__powerUp)
                up.start()
    
        def __powerUp(self):
            if not hasattr(self, "_down"):
                return
            self._down.join()
            # do something
            del self._down
    
    85 cũng có bộ xử lý nhiều bước. Mỗi bước này là một hướng dẫn riêng cho bộ xử lý.

  2. Hệ điều hành có thể hoán đổi chủ đề nào đang chạy bất cứ lúc nào. Một chủ đề có thể được hoán đổi sau bất kỳ hướng dẫn nhỏ nào. Điều này có nghĩa là một chủ đề có thể được đưa vào giấc ngủ để cho một chủ đề khác chạy ở giữa một câu lệnh Python.

Hãy cùng nhìn vào điều này một cách chi tiết. REP REP bên dưới hiển thị một hàm có tham số và gia tăng nó:

>>>

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
6

Ví dụ thay thế sử dụng

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
86 từ thư viện tiêu chuẩn Python để hiển thị các bước nhỏ hơn mà bộ xử lý thực hiện để thực hiện chức năng của bạn. Nó thực hiện một
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
87 của giá trị dữ liệu
import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)
1, nó thực hiện một
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
89, và sau đó nó sử dụng
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
90 để thêm các giá trị đó lại với nhau.

Chúng tôi dừng lại ở đây vì một lý do cụ thể. Đây là điểm trong

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
08 ở trên khi
$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
5 buộc các luồng phải chuyển đổi. Hoàn toàn có thể, thỉnh thoảng, hệ điều hành sẽ chuyển đổi các luồng tại điểm chính xác đó ngay cả khi không có
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
93, nhưng cuộc gọi đến
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
93 làm cho nó xảy ra mỗi lần.

Như bạn đã biết ở trên, hệ điều hành có thể trao đổi các luồng bất cứ lúc nào. Bạn đã đi xuống danh sách này để tuyên bố được đánh dấu

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
95. Nếu hệ điều hành hoán đổi luồng này và chạy một luồng khác cũng sửa đổi
import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)
1, thì khi luồng này tiếp tục, nó sẽ ghi đè lên
import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)
1 với giá trị không chính xác.

Về mặt kỹ thuật, ví dụ này đã giành được một điều kiện cuộc đua vì

import logging
import threading
import time

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    threads = list()
    for index in range(3):
        logging.info("Main    : create and start thread %d.", index)
        x = threading.Thread(target=thread_function, args=(index,))
        threads.append(x)
        x.start()

    for index, thread in enumerate(threads):
        logging.info("Main    : before joining thread %d.", index)
        thread.join()
        logging.info("Main    : thread %d done", index)
1 là địa phương đến
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
99. Tuy nhiên, nó minh họa làm thế nào một luồng có thể bị gián đoạn trong một hoạt động Python duy nhất. Cùng một tải, sửa đổi, tập hợp các hoạt động cũng xảy ra trên các giá trị toàn cầu và được chia sẻ. Bạn có thể khám phá với mô -đun
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
86 và tự chứng minh điều đó.

Nó rất hiếm khi có được một điều kiện cuộc đua như thế này xảy ra, nhưng hãy nhớ rằng một sự kiện không thường xuyên đã chiếm được hàng triệu lần lặp lại có thể xảy ra. Sự hiếm hoi của các điều kiện chủng tộc này làm cho chúng, khó gỡ lỗi hơn nhiều so với các lỗi thông thường.

Bây giờ trở lại hướng dẫn theo lịch trình thường xuyên của bạn!

Bây giờ bạn đã thấy một điều kiện cuộc đua đang hoạt động, hãy để tìm ra cách giải quyết chúng!

Đồng bộ hóa cơ bản bằng cách sử dụng from multiprocessing.pool import ThreadPool # This is the top level function called by other objects def reboot(self): # setup your thread pool: reboot_pool = ThreadPool() # - First thread calls the __powerDown() function power_down = reboot_pool.apply_async(self.__powerDown()) # this will block until it finishes power_down.get() # - Secod thread calls the __powerUp() function power_up = reboot_pool.apply_async(self.__powerUp()) # block until __powerUp() thread finishes power_up.get() def __powerDown(self): # What to put here? pass def __powerUp(self): # What to put here? pass 01

Có một số cách để tránh hoặc giải quyết các điều kiện chủng tộc. Bạn đã giành chiến thắng nhìn vào tất cả chúng ở đây, nhưng có một cặp được sử dụng thường xuyên. Hãy bắt đầu với

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01.

Để giải quyết điều kiện cuộc đua của bạn ở trên, bạn cần tìm cách chỉ cho phép một luồng tại một thời điểm vào phần đọc biến đổi-viết trong mã của bạn. Cách phổ biến nhất để làm điều này được gọi là

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 trong Python. Trong một số ngôn ngữ khác, ý tưởng tương tự này được gọi là
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
04. Mutex xuất phát từ loại trừ lẫn nhau, đó chính xác là những gì
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 làm.

Một

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 là một đối tượng hoạt động như một đường chuyền hội trường. Chỉ có một luồng tại một thời điểm có thể có
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01. Bất kỳ chủ đề nào khác muốn
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 phải đợi cho đến khi chủ sở hữu của
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 từ bỏ.

Các chức năng cơ bản để làm điều này là

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
10 và
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11. Một chủ đề sẽ gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
12 để lấy khóa. Nếu khóa đã được giữ, luồng gọi sẽ đợi cho đến khi nó được phát hành. Có một điểm quan trọng ở đây. Nếu một chủ đề nhận được khóa nhưng không bao giờ trả lại, chương trình của bạn sẽ bị kẹt. Bạn sẽ đọc thêm về điều này sau.

May mắn thay, Python sườn

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 cũng sẽ hoạt động như một người quản lý ngữ cảnh, vì vậy bạn có thể sử dụng nó trong một câu lệnh
$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done
2 và nó được phát hành tự động khi khối
$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done
2 thoát ra vì bất kỳ lý do gì.

Hãy cùng nhìn vào

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
06 với
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 được thêm vào nó. Hàm gọi vẫn giữ nguyên:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
7

Khác với việc thêm một loạt các bản ghi nhật ký để bạn có thể thấy việc khóa rõ ràng hơn, thay đổi lớn ở đây là thêm một thành viên có tên là

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
18, là đối tượng
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
19.
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
18 này được khởi tạo ở trạng thái không khóa và bị khóa và phát hành bởi câu lệnh
$ ./multiple_threads.py
Main    : create and start thread 0.
Thread 0: starting
Main    : create and start thread 1.
Thread 1: starting
Main    : create and start thread 2.
Thread 2: starting
Main    : before joining thread 0.
Thread 2: finishing
Thread 1: finishing
Thread 0: finishing
Main    : thread 0 done
Main    : before joining thread 1.
Main    : thread 1 done
Main    : before joining thread 2.
Main    : thread 2 done
2.

Ở đây, điều đáng chú ý ở đây là chuỗi chạy chức năng này sẽ giữ được

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 đó cho đến khi nó hoàn toàn cập nhật cơ sở dữ liệu. Trong trường hợp này, điều đó có nghĩa là nó sẽ giữ
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 trong khi nó sao chép, cập nhật, ngủ và sau đó ghi giá trị trở lại cơ sở dữ liệu.

Nếu bạn chạy phiên bản này với việc đăng nhập được đặt thành cấp cảnh báo, bạn sẽ thấy điều này:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
8

Nhìn kìa. Chương trình của bạn cuối cùng cũng hoạt động!

Bạn có thể bật đăng nhập đầy đủ bằng cách đặt cấp độ thành

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
24 bằng cách thêm câu lệnh này sau khi bạn định cấu hình đầu ra ghi nhật ký trong
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
6:

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
9

Chạy chương trình này với việc đăng nhập

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
24 BẬT có vẻ như thế này:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
0

Trong đầu ra này, bạn có thể thấy

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
04 có được khóa và vẫn đang giữ nó khi nó đi ngủ.
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 sau đó bắt đầu và cố gắng để có được cùng một khóa. Bởi vì
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
04 vẫn đang giữ nó,
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down
03 phải chờ đợi. Đây là loại trừ lẫn nhau mà
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 cung cấp.

Nhiều ví dụ trong phần còn lại của bài viết này sẽ có mức ghi nhật ký

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
32 và
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
24. Chúng tôi thường chỉ hiển thị đầu ra cấp
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
32, vì nhật ký
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
24 có thể khá dài. Hãy thử các chương trình với việc đăng nhập bật lên và xem những gì họ làm.

Bế tắc

Trước khi bạn tiếp tục, bạn nên xem xét một vấn đề phổ biến khi sử dụng

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
36. Như bạn đã thấy, nếu
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 đã được mua lại, cuộc gọi thứ hai đến
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
10 sẽ đợi cho đến khi luồng đang giữ cuộc gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11. Bạn nghĩ điều gì xảy ra khi bạn chạy mã này:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
1

Khi chương trình gọi

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
41 lần thứ hai, nó đã chờ đợi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 được phát hành. Trong ví dụ này, bạn có thể sửa chữa bế tắc bằng cách xóa cuộc gọi thứ hai, nhưng bế tắc thường xảy ra từ một trong hai điều tinh tế:

  1. Một lỗi triển khai trong đó
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    01 không được phát hành đúng cách
  2. Một vấn đề thiết kế trong đó một chức năng tiện ích cần được gọi bởi các chức năng có thể hoặc chưa có
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    01

Tình huống đầu tiên đôi khi xảy ra, nhưng sử dụng

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 làm trình quản lý bối cảnh làm giảm đáng kể mức độ thường xuyên. Bạn nên viết mã bất cứ khi nào có thể sử dụng các nhà quản lý ngữ cảnh, vì họ giúp tránh các tình huống trong đó một ngoại lệ bỏ qua cuộc gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11.

Vấn đề thiết kế có thể là một chút khó khăn hơn trong một số ngôn ngữ. Rất may, luồng Python có một đối tượng thứ hai, được gọi là

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
47, được thiết kế cho tình huống này. Nó cho phép một luồng đến
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
10 một
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
47 nhiều lần trước khi nó gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11. Chủ đề đó vẫn được yêu cầu gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11 cùng số lần được gọi là
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
10, nhưng dù sao nó cũng nên làm điều đó.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 và
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
47 là hai trong số các công cụ cơ bản được sử dụng trong lập trình ren để ngăn chặn các điều kiện chủng tộc. Có một vài hoạt động khác theo những cách khác nhau. Trước khi bạn nhìn vào chúng, hãy để Lừa chuyển sang một miền vấn đề hơi khác.

Nhà sản xuất-người tiêu dùng

Vấn đề của nhà sản xuất là một vấn đề khoa học máy tính tiêu chuẩn được sử dụng để xem xét các vấn đề đồng bộ hóa luồng hoặc quy trình. Bạn sẽ xem xét một biến thể của nó để có được một số ý tưởng về những gì nguyên thủy mà mô -đun Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8 cung cấp.

Trong ví dụ này, bạn sẽ tưởng tượng một chương trình cần đọc tin nhắn từ mạng và viết chúng vào đĩa. Chương trình không yêu cầu một tin nhắn khi nó muốn. Nó phải được lắng nghe và chấp nhận tin nhắn khi chúng đến. Các tin nhắn sẽ không đến với tốc độ thường xuyên, nhưng sẽ đến trong các vụ nổ. Phần này của chương trình được gọi là nhà sản xuất.

Mặt khác, một khi bạn có một tin nhắn, bạn cần viết nó vào cơ sở dữ liệu. Truy cập cơ sở dữ liệu chậm, nhưng đủ nhanh để theo kịp tốc độ trung bình của tin nhắn. Nó không đủ nhanh để theo kịp khi một loạt các tin nhắn xuất hiện. Phần này là người tiêu dùng.

Ở giữa nhà sản xuất và người tiêu dùng, bạn sẽ tạo ra một

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56 sẽ là phần thay đổi khi bạn tìm hiểu về các đối tượng đồng bộ hóa khác nhau.

Đó là bố cục cơ bản. Hãy cùng nhìn vào một giải pháp bằng cách sử dụng

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01. Nó không hoạt động hoàn hảo, nhưng nó sử dụng các công cụ mà bạn đã biết, vì vậy nó là một nơi tốt để bắt đầu.

Nhà sản xuất người tiêu dùng sử dụng from multiprocessing.pool import ThreadPool # This is the top level function called by other objects def reboot(self): # setup your thread pool: reboot_pool = ThreadPool() # - First thread calls the __powerDown() function power_down = reboot_pool.apply_async(self.__powerDown()) # this will block until it finishes power_down.get() # - Secod thread calls the __powerUp() function power_up = reboot_pool.apply_async(self.__powerUp()) # block until __powerUp() thread finishes power_up.get() def __powerDown(self): # What to put here? pass def __powerUp(self): # What to put here? pass 01

Vì đây là một bài viết về Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8, và vì bạn vừa đọc về nguyên thủy
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01, chúng ta hãy cố gắng giải quyết vấn đề này bằng hai luồng bằng cách sử dụng
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 hoặc hai.

Thiết kế chung là có một chủ đề

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 đọc từ mạng giả và đặt thông điệp vào một
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
2

Để tạo tin nhắn giả,

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 có số ngẫu nhiên từ một đến một trăm. Nó gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
65 trên
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66 để gửi nó đến
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 cũng sử dụng giá trị
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
69 để báo hiệu cho người tiêu dùng dừng sau khi nó đã gửi mười giá trị. Đây là một chút khó xử, nhưng đừng lo lắng, bạn sẽ thấy cách để thoát khỏi giá trị
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
69 này sau khi bạn làm việc trong ví dụ này.

Ở phía bên kia của

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66 là người tiêu dùng:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
3

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 đọc một thông báo từ
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66 và ghi nó vào cơ sở dữ liệu giả, trong trường hợp này chỉ đang in nó vào màn hình. Nếu nó nhận được giá trị
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
69, nó sẽ trả về từ hàm, sẽ chấm dứt luồng.

Trước khi bạn nhìn vào phần thực sự thú vị,

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56, ở đây, phần
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
6, tạo ra các chủ đề này:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
4

Điều này trông khá quen thuộc vì nó gần với mã

x = threading.Thread(target=thread_function, args=(1,), daemon=True)
6 trong các ví dụ trước.

Hãy nhớ rằng bạn có thể bật

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
24 đăng nhập để xem tất cả các tin nhắn ghi nhật ký bằng cách không đưa ra dòng này:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
5

Có thể đáng để đi qua các tin nhắn đăng nhập

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
24 để xem chính xác nơi mỗi luồng thu và phát hành các khóa.

Bây giờ, hãy để Lừa xem

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56 chuyển tin nhắn từ
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 đến
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
6

Woah! Đó là rất nhiều mã. Một tỷ lệ phần trăm khá cao trong số đó chỉ là các câu lệnh ghi nhật ký để giúp dễ dàng nhìn thấy những gì xảy ra khi bạn chạy nó. Ở đây, cùng một mã với tất cả các câu lệnh ghi nhật ký đã bị xóa:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
7

Điều đó có vẻ dễ quản lý hơn một chút.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56 trong phiên bản mã của bạn có ba thành viên:

  1. from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    84 lưu trữ thông điệp để vượt qua.
    stores the message to pass.
  2. from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    85 là đối tượng
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    86 hạn chế quyền truy cập vào thông báo bằng luồng
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    62.
    is a
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    86 object that restricts access to the message by the
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    62 thread.
  3. from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    88 cũng là một
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    86 hạn chế quyền truy cập vào thông báo bằng chuỗi
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    67.
    is also a
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    86 that restricts access to the message by the
    from multiprocessing.pool import ThreadPool
    
    # This is the top level function called by other objects
    def reboot(self):
        # setup your thread pool:
        reboot_pool = ThreadPool()
        # - First thread calls the __powerDown() function
        power_down = reboot_pool.apply_async(self.__powerDown())
        # this will block until it finishes
        power_down.get()
        # - Secod thread calls the __powerUp() function
        power_up = reboot_pool.apply_async(self.__powerUp())
        #   block until __powerUp() thread finishes
        power_up.get()
    
    def __powerDown(self):
        # What to put here?
        pass
    
    def __powerUp(self):
        # What to put here?
        pass
    
    67 thread.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
91 khởi tạo ba thành viên này và sau đó gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
10 trên
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
88. Đây là trạng thái bạn muốn bắt đầu.
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 được phép thêm một tin nhắn mới, nhưng
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 cần phải đợi cho đến khi có tin nhắn.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
96 và
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
97 gần như đối lập.
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
96 gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
10 trên
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
00. Đây là cuộc gọi sẽ làm cho
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 đợi cho đến khi một tin nhắn đã sẵn sàng.

Khi

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 đã có được
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
88, nó sẽ sao chép giá trị trong
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
84 và sau đó gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11 trên
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
85. Phát hành khóa này là những gì cho phép
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 chèn tin nhắn tiếp theo vào
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66.

Trước khi bạn tiếp tục

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
65, có một điều gì đó tinh tế đang diễn ra trong
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
96 mà khá dễ bỏ lỡ. Nó có vẻ hấp dẫn khi loại bỏ
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
11 và chỉ có chức năng kết thúc với
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
12. Xem nếu bạn có thể tìm ra lý do tại sao bạn không muốn làm điều đó trước khi tiếp tục.

Ở đây, câu trả lời. Ngay khi

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 gọi
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
14, nó có thể được hoán đổi và
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 có thể bắt đầu chạy. Điều đó có thể xảy ra trước khi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11 trở lại! Điều này có nghĩa là có một khả năng nhỏ là khi hàm trả về
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
17, đó thực sự có thể là thông báo tiếp theo được tạo, vì vậy bạn sẽ mất tin nhắn đầu tiên. Đây là một ví dụ khác về một điều kiện chủng tộc.

Chuyển sang

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
65, bạn có thể thấy phía đối diện của giao dịch.
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 sẽ gọi cái này với một tin nhắn. Nó sẽ có được
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
85, đặt
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
84 và cuộc gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11 sau đó
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
00, sẽ cho phép
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 đọc giá trị đó.

Hãy cùng chạy mã có bộ ghi nhật ký thành

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
32 và xem nó trông như thế nào:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
8

Lúc đầu, bạn có thể thấy kỳ lạ là nhà sản xuất nhận được hai tin nhắn trước khi người tiêu dùng chạy. Nếu bạn nhìn lại

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 và
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
65, bạn sẽ nhận thấy rằng nơi duy nhất nó sẽ chờ một
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 là khi nó cố gắng đưa tin nhắn vào đường ống. Điều này được thực hiện sau khi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 nhận được tin nhắn và nhật ký rằng nó có nó.

Khi

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 cố gắng gửi tin nhắn thứ hai này, nó sẽ gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
65 lần thứ hai và nó sẽ chặn.

Hệ điều hành có thể hoán đổi các luồng bất cứ lúc nào, nhưng thường cho phép mỗi luồng có một lượng thời gian hợp lý để chạy trước khi hoán đổi nó. Đó là lý do tại sao

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 thường chạy cho đến khi nó chặn trong cuộc gọi thứ hai tới
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
65.

Tuy nhiên, khi một luồng bị chặn, hệ điều hành sẽ luôn trao đổi nó và tìm một luồng khác để chạy. Trong trường hợp này, chủ đề duy nhất khác có bất cứ điều gì để làm là

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
96, đọc tin nhắn và gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11 trên
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
85, do đó cho phép
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 chạy lại vào thời gian tiếp theo được hoán đổi.

Lưu ý rằng tin nhắn đầu tiên là

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
40 và đó chính xác là những gì
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 đọc, mặc dù
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 đã tạo ra thông báo
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
43.

Mặc dù nó hoạt động cho thử nghiệm hạn chế này, nhưng nó không phải là một giải pháp tuyệt vời cho vấn đề người tiêu dùng sản xuất nói chung vì nó chỉ cho phép một giá trị duy nhất trong đường ống tại một thời điểm. Khi

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 nhận được một tin nhắn, nó sẽ không có nơi nào để đặt chúng.

Hãy cùng chuyển sang một cách tốt hơn để giải quyết vấn đề này, sử dụng

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45.

Nhà sản xuất người tiêu dùng sử dụng 1import logging 2import threading 3import time 4 5def thread_function(name): 6 logging.info("Thread %s: starting", name) 7 time.sleep(2) 8 logging.info("Thread %s: finishing", name) 9 10if __name__ == "__main__": 11 format = "%(asctime)s: %(message)s" 12 logging.basicConfig(format=format, level=logging.INFO, 13 datefmt="%H:%M:%S") 14 15 logging.info("Main : before creating thread") 16 x = threading.Thread(target=thread_function, args=(1,)) 17 logging.info("Main : before running thread") 18 x.start() 19 logging.info("Main : wait for the thread to finish") 20 # x.join() 21 logging.info("Main : all done") 45

Nếu bạn muốn có thể xử lý nhiều hơn một giá trị trong đường ống tại một thời điểm, bạn sẽ cần một cấu trúc dữ liệu cho đường ống cho phép số phát triển và thu nhỏ khi dữ liệu tăng từ

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62.

Thư viện tiêu chuẩn Python sườn có mô -đun

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
48, do đó, có lớp
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45. Hãy để thay đổi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56 để sử dụng
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45 thay vì chỉ là một biến được bảo vệ bởi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01. Bạn cũng sẽ sử dụng một cách khác để ngăn chặn các luồng công nhân bằng cách sử dụng một nguyên thủy khác với Python
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8,
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
54.

Hãy bắt đầu với

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
54. Đối tượng
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
56 cho phép một luồng báo hiệu
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
57 trong khi nhiều luồng khác có thể chờ đợi
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
57 xảy ra. Việc sử dụng chính trong mã này là các luồng đang chờ sự kiện không nhất thiết phải dừng những gì họ đang làm, họ chỉ có thể kiểm tra trạng thái của
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
54 mỗi lần.

Việc kích hoạt sự kiện có thể là nhiều điều. Trong ví dụ này, chủ đề chính sẽ chỉ ngủ một lúc và sau đó

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
60 nó:

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
9

Những thay đổi duy nhất ở đây là việc tạo đối tượng

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
57 trên dòng 8, vượt qua
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
57 dưới dạng tham số trên các dòng 10 và 11, và phần cuối cùng trên các dòng 13 đến 15, ngủ trong một giây, đăng nhập một tin nhắn, sau đó gọi
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
60 về sự kiện.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 cũng không phải thay đổi quá nhiều:

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
0

Bây giờ nó sẽ lặp lại cho đến khi nó thấy rằng sự kiện được đặt trên dòng 3. Nó cũng không còn đặt giá trị

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
69 vào
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 đã phải thay đổi thêm một chút:

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
1

Mặc dù bạn phải lấy mã liên quan đến giá trị

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
69, bạn đã phải thực hiện một điều kiện
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
69 phức tạp hơn một chút. Nó không chỉ lặp lại cho đến khi
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
57 được đặt, mà còn cần phải tiếp tục lặp cho đến khi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66 được làm trống.

Đảm bảo hàng đợi trống trước khi người tiêu dùng hoàn thành ngăn chặn một vấn đề thú vị khác. Nếu

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 thoát ra trong khi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66 có tin nhắn trong đó, có hai điều xấu có thể xảy ra. Đầu tiên là bạn mất những tin nhắn cuối cùng đó, nhưng điều nghiêm trọng hơn là
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 có thể bị bắt khi cố gắng thêm một tin nhắn vào hàng đợi đầy đủ và không bao giờ quay lại.

Điều này xảy ra nếu

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
57 được kích hoạt sau khi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 đã kiểm tra điều kiện
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
77 nhưng trước khi nó gọi
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
78.

Nếu điều đó xảy ra, người tiêu dùng có thể thức dậy và thoát ra với hàng đợi vẫn hoàn toàn đầy đủ.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 sau đó sẽ gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
65 sẽ đợi cho đến khi có không gian trên hàng đợi cho tin nhắn mới.
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 đã thoát ra, vì vậy điều này sẽ không xảy ra và
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 sẽ không thoát ra.

Phần còn lại của

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 sẽ trông quen thuộc.

Tuy nhiên,

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56 đã thay đổi đáng kể:

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
2

Bạn có thể thấy rằng

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56 là một lớp con của
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
86.
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45 có tham số tùy chọn khi khởi tạo để chỉ định kích thước tối đa của hàng đợi.

Nếu bạn đưa ra một số dương cho

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
88, nó sẽ giới hạn hàng đợi ở số lượng phần tử đó, khiến
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
89 chặn cho đến khi có ít hơn các phần tử
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
88. Nếu bạn không chỉ định
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
88, thì hàng đợi sẽ phát triển đến giới hạn bộ nhớ máy tính của bạn.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
96 và
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
65 nhỏ hơn nhiều. Về cơ bản, chúng bao bọc
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
94 và
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
89 trên
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45. Bạn có thể tự hỏi nơi tất cả các mã khóa ngăn chặn các luồng gây ra các điều kiện chủng tộc đã đi.

Các nhà phát triển cốt lõi đã viết thư viện tiêu chuẩn biết rằng

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45 thường được sử dụng trong môi trường đa luồng và kết hợp tất cả các mã khóa đó bên trong chính
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45.
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45 là an toàn cho luồng.

Chạy chương trình này trông giống như sau:

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
3

Nếu bạn đọc qua đầu ra trong ví dụ của tôi, bạn có thể thấy một số điều thú vị xảy ra. Ngay trên đỉnh, bạn có thể thấy

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 phải tạo năm tin nhắn và đặt bốn trong số chúng vào hàng đợi. Nó đã được trao đổi bởi hệ điều hành trước khi nó có thể đặt cái thứ năm.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 sau đó chạy và rút tin nhắn đầu tiên. Nó đã in ra thông điệp đó cũng như hàng đợi sâu như thế nào vào thời điểm đó:

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
4

Đây là cách bạn biết rằng tin nhắn thứ năm đã không đưa nó vào

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66. Hàng đợi giảm xuống kích thước ba sau khi một tin nhắn được xóa. Bạn cũng biết rằng
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
48 có thể chứa mười tin nhắn, vì vậy chuỗi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 đã không bị chặn bởi
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
48. Nó đã được trao đổi bởi hệ điều hành.

Khi chương trình bắt đầu kết thúc, bạn có thể thấy luồng chính tạo ra

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
57 khiến
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 thoát ra ngay lập tức.
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 vẫn có một loạt các công việc làm, vì vậy nó tiếp tục chạy cho đến khi nó đã làm sạch
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
66.

Hãy thử chơi với các kích thước hàng đợi khác nhau và các cuộc gọi đến

$ ./single_thread.py
Main    : before creating thread
Main    : before running thread
Thread 1: starting
Main    : wait for the thread to finish
Main    : all done
Thread 1: finishing
5 trong
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
62 hoặc
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
67 để mô phỏng thời gian truy cập mạng hoặc đĩa dài hơn tương ứng. Ngay cả những thay đổi nhỏ đối với các yếu tố này của chương trình sẽ tạo ra sự khác biệt lớn trong kết quả của bạn.

Đây là một giải pháp tốt hơn nhiều cho vấn đề người tiêu dùng sản xuất, nhưng bạn có thể đơn giản hóa nó nhiều hơn.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
56 thực sự không cần thiết cho vấn đề này. Một khi bạn lấy đi việc khai thác, nó sẽ trở thành
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
86.

Ở đây, những gì mã cuối cùng trông giống như bằng cách sử dụng trực tiếp

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
86:

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
5

Điều đó dễ đọc hơn và cho thấy cách sử dụng các nguyên thủy tích hợp Python có thể đơn giản hóa một vấn đề phức tạp.

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
01 và
 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
45 là các lớp tiện dụng để giải quyết các vấn đề đồng thời, nhưng có những lớp khác được cung cấp bởi thư viện tiêu chuẩn. Trước khi bạn kết thúc hướng dẫn này, hãy để một cuộc khảo sát nhanh về một số trong số họ.

Đối tượng luồng

Có một vài nguyên thủy được cung cấp bởi mô -đun Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8. Mặc dù bạn đã không cần những điều này cho các ví dụ ở trên, nhưng chúng có thể có ích trong các trường hợp sử dụng khác nhau, vì vậy, thật tốt khi làm quen với chúng.

Semaphore

Đối tượng Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8 đầu tiên nhìn vào là
x = threading.Thread(target=thread_function, args=(1,))
x.start()
20. A
x = threading.Thread(target=thread_function, args=(1,))
x.start()
21 là một bộ đếm với một vài thuộc tính đặc biệt. Điều đầu tiên là việc đếm là nguyên tử. Điều này có nghĩa là có một đảm bảo rằng hệ điều hành sẽ không trao đổi luồng ở giữa tăng hoặc giảm bộ đếm.

Bộ đếm bên trong được tăng lên khi bạn gọi

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11 và giảm khi bạn gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
10.

Thuộc tính đặc biệt tiếp theo là nếu một luồng gọi

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
10 khi bộ đếm bằng không, luồng đó sẽ chặn cho đến khi một luồng khác gọi
from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass
11 và tăng bộ đếm lên một.

Semaphores thường được sử dụng để bảo vệ một tài nguyên có công suất hạn chế. Một ví dụ sẽ là nếu bạn có một nhóm kết nối và muốn giới hạn kích thước của nhóm đó ở một số cụ thể.

Hẹn giờ

Một

x = threading.Thread(target=thread_function, args=(1,))
x.start()
26 là một cách để lên lịch cho một chức năng được gọi sau một khoảng thời gian nhất định đã trôi qua. Bạn tạo một
x = threading.Thread(target=thread_function, args=(1,))
x.start()
27 bằng cách chuyển trong một số giây để chờ đợi và một chức năng để gọi:

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
6

Bạn bắt đầu

x = threading.Thread(target=thread_function, args=(1,))
x.start()
27 bằng cách gọi
x = threading.Thread(target=thread_function, args=(1,))
x.start()
7. Hàm sẽ được gọi trên một chủ đề mới tại một số điểm sau thời gian được chỉ định, nhưng lưu ý rằng không có lời hứa rằng nó sẽ được gọi chính xác tại thời điểm bạn muốn.

Nếu bạn muốn dừng

x = threading.Thread(target=thread_function, args=(1,))
x.start()
27 mà bạn đã bắt đầu, bạn có thể hủy nó bằng cách gọi
x = threading.Thread(target=thread_function, args=(1,))
x.start()
31. Gọi
x = threading.Thread(target=thread_function, args=(1,))
x.start()
31 sau khi
x = threading.Thread(target=thread_function, args=(1,))
x.start()
27 đã kích hoạt không làm gì và không tạo ra một ngoại lệ.

Một

x = threading.Thread(target=thread_function, args=(1,))
x.start()
27 có thể được sử dụng để nhắc người dùng hành động sau một khoảng thời gian cụ thể. Nếu người dùng thực hiện hành động trước khi
x = threading.Thread(target=thread_function, args=(1,))
x.start()
27 hết hạn,
x = threading.Thread(target=thread_function, args=(1,))
x.start()
31 có thể được gọi.

Rào chắn

Một

x = threading.Thread(target=thread_function, args=(1,))
x.start()
37 có thể được sử dụng để giữ một số lượng cố định các luồng đồng bộ. Khi tạo
x = threading.Thread(target=thread_function, args=(1,))
x.start()
38, người gọi phải chỉ định số lượng chủ đề sẽ được đồng bộ hóa trên nó. Mỗi luồng gọi
x = threading.Thread(target=thread_function, args=(1,))
x.start()
39 trên
x = threading.Thread(target=thread_function, args=(1,))
x.start()
38. Tất cả chúng sẽ vẫn bị chặn cho đến khi số lượng luồng được chỉ định đang chờ, và sau đó tất cả được phát hành cùng một lúc.

Hãy nhớ rằng các chủ đề được lên lịch bởi hệ điều hành, mặc dù tất cả các luồng được phát hành đồng thời, chúng sẽ được lên kế hoạch để chạy một lần.

Một cách sử dụng cho

x = threading.Thread(target=thread_function, args=(1,))
x.start()
38 là cho phép một nhóm các luồng tự khởi tạo. Có các luồng chờ trên
x = threading.Thread(target=thread_function, args=(1,))
x.start()
38 sau khi chúng được khởi tạo sẽ đảm bảo rằng không có luồng nào bắt đầu chạy trước khi tất cả các luồng được hoàn thành với khởi tạo của chúng.

Kết luận: Chủ đề trong Python

Bây giờ bạn đã thấy nhiều về những gì Python

 1import logging
 2import threading
 3import time
 4
 5def thread_function(name):
 6    logging.info("Thread %s: starting", name)
 7    time.sleep(2)
 8    logging.info("Thread %s: finishing", name)
 9
10if __name__ == "__main__":
11    format = "%(asctime)s: %(message)s"
12    logging.basicConfig(format=format, level=logging.INFO,
13                        datefmt="%H:%M:%S")
14
15    logging.info("Main    : before creating thread")
16    x = threading.Thread(target=thread_function, args=(1,))
17    logging.info("Main    : before running thread")
18    x.start()
19    logging.info("Main    : wait for the thread to finish")
20    # x.join()
21    logging.info("Main    : all done")
8 cung cấp và một số ví dụ về cách xây dựng các chương trình có luồng và các vấn đề họ giải quyết. Bạn cũng đã thấy một vài trường hợp về các vấn đề phát sinh khi viết và gỡ lỗi các chương trình có chủ đề.

Nếu bạn muốn khám phá các tùy chọn khác cho sự đồng thời trong Python, hãy kiểm tra tăng tốc chương trình Python của bạn với sự đồng thời.

Nếu bạn quan tâm đến việc thực hiện một lần lặn sâu trên mô -đun

x = threading.Thread(target=thread_function, args=(1,))
x.start()
0, hãy đọc Async IO trong Python: một hướng dẫn hoàn chỉnh.

Dù bạn làm gì, bây giờ bạn có thông tin và sự tự tin mà bạn cần viết các chương trình bằng cách sử dụng chuỗi Python!

Đặc biệt cảm ơn độc giả JL Diaz vì đã giúp dọn dẹp phần giới thiệu.

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để làm sâu sắc thêm sự hiểu biết của bạn: Xây dựng bằng Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Threading in Python

Chủ đề có thể sinh ra chủ đề Python không?

Chủ đề trong Python.Một luồng là một chuỗi các hướng dẫn đang được thực thi trong bối cảnh của một quá trình.Một quy trình có thể sinh ra nhiều luồng nhưng tất cả chúng sẽ chia sẻ cùng một bộ nhớ.One process can spawn multiple threads but all of them will be sharing the same memory.

Một chủ đề có thể sinh ra một chủ đề khác không?

Đúng.Tuy nhiên, vấn đề điển hình là công việc/chủ đề không bị hạn chế.Sử dụng phương pháp bạn đã phác thảo, thật dễ dàng để sinh ra nhiều luồng và có số lượng chủ đề cao phi logic cho công việc phải được thực hiện trên một số lượng lõi hạn chế.it's easy to spawn many threads and have an illogically high number of threads for the work which must be executed on a limited number of cores.

Hai luồng có thể gọi cùng một hàm python không?

Một luồng có thể thực thi một hàm song song với các luồng khác.Mỗi luồng chia sẻ cùng một mã, dữ liệu và tệp trong khi chúng có ngăn xếp và thanh ghi riêng của họ.. Each thread shares the same code, data, and files while they have their own stack and registers.

Có bao nhiêu chủ đề có thể được sinh ra python?

Mỗi lõi CPU có thể có tối đa hai luồng nếu CPU của bạn có kích hoạt đa/siêu luồng.Bạn có thể tìm kiếm bộ xử lý CPU của riêng bạn để tìm hiểu thêm.Đối với người dùng Mac, bạn có thể tìm hiểu từ Giới thiệu> Báo cáo hệ thống.up to two threads if your CPU has multi/hyper-threading enabled. You can search for your own CPU processor to find out more. For Mac users, you can find out from About > System Report.