Hướng dẫn python threadpoolexecutor global variable - biến toàn cục threadpoolexecutor trong python

Tôi mới song song hóa nói chung và đồng thời. Đặc biệt. Tôi muốn đánh giá tập lệnh của mình và so sánh sự khác biệt giữa việc sử dụng các luồng và quy trình, nhưng tôi thấy rằng tôi thậm chí không thể chạy điều đó vì khi sử dụng ProcessPoolExecutor, tôi không thể sử dụng các biến toàn cầu của mình.

Mã sau đây sẽ xuất ra Helloas tôi mong đợi, nhưng khi bạn thay đổi

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
0 cho ProcessPoolExecutor, nó sẽ xuất ra
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
2.

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def process[]:
    print[greeting]

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None


def init[]:
    global greeting
    greeting = 'Hello'

    return None

if __name__ == '__main__':
    init[]
    main[]

Tôi không hiểu tại sao đây là trường hợp. Trong chương trình thực của tôi, init được sử dụng để đặt các biến toàn cầu thành các đối số CLI và có rất nhiều trong số chúng. Do đó, thông qua chúng như những lập luận dường như không được khuyến nghị. Vậy làm cách nào để chuyển các biến toàn cầu đó cho từng quy trình/luồng một cách chính xác?

Tôi biết rằng tôi có thể thay đổi mọi thứ xung quanh, điều này sẽ hoạt động, nhưng tôi không hiểu tại sao. Ví dụ. Các hoạt động sau đây cho cả hai người thực thi, nhưng điều đó cũng có nghĩa là việc khởi tạo toàn cầu phải xảy ra cho mọi trường hợp.

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]

Vì vậy, câu hỏi chính của tôi là, những gì đang thực sự xảy ra. Tại sao mã này hoạt động với các chủ đề chứ không phải với các quy trình? Và, làm thế nào để tôi truyền chính xác các toàn cầu đã đặt cho từng quy trình/luồng mà không cần phải khởi tạo lại chúng cho mọi trường hợp?what is actually happening. Why does this code work with threads and not with processes? And, how do I correctly pass set globals to each process/thread without having to re-initialise them for every instance?

[Lưu ý bên: Vì tôi đã đọc rằng đồng thời.

Lớn lên khi một hoạt động được thực hiện trong một tương lai không được phép trong trạng thái hiện tại.

Mới trong phiên bản 3.8. Lib/concurrent/futures/thread.py and Lib/concurrent/futures/process.py

ExceptionConcurrent.futures.thread.brokenthreadpool¶

Có nguồn gốc từ

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
35, lớp ngoại lệ này được nâng lên khi một trong những công nhân của
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
4 đã thất bại khi khởi tạo.

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

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

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
7 và
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
8. Xem các nền tảng Webassugging để biết thêm thông tin.WebAssembly platforms for more information.

Đối tượng thực thi

classconceren.futures.executor¶ concurrent.futures.Executor

Một lớp trừu tượng cung cấp các phương thức để thực hiện các cuộc gọi không đồng bộ. Nó không nên được sử dụng trực tiếp, mà thông qua các lớp con bê tông của nó.

Gửi [fn, /, *args, ** kwargs] ¶[fn, /, *args, **kwargs]

Lịch trình được gọi, FN, được thực thi là

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
9 và trả về một đối tượng
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
0 đại diện cho việc thực thi người được gọi.

with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]

bản đồ [func, *iterables, thời gian chờ = không, chunksize = 1] ¶[func, *iterables, timeout=None, chunksize=1]

Tương tự như

with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
1 ngoại trừ:

  • Các vòng lặp được thu thập ngay lập tức thay vì lười biếng;

  • Func được thực hiện không đồng bộ và một số cuộc gọi đến func có thể được thực hiện đồng thời.

Trình lặp được trả về tăng

with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
2 nếu
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
3 được gọi và kết quả không có sẵn sau khi hết thời gian chờ từ cuộc gọi ban đầu đến
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
4. Thời gian chờ có thể là một int hoặc một chiếc phao. Nếu thời gian chờ không được chỉ định hoặc
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
5, không có giới hạn thời gian chờ.

Nếu một cuộc gọi func làm tăng một ngoại lệ, thì ngoại lệ đó sẽ được tăng lên khi giá trị của nó được lấy từ iterator.

Khi sử dụng

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
5, phương pháp này đã cắt các vòng lặp thành một số khối mà nó gửi đến nhóm dưới dạng các nhiệm vụ riêng biệt. Kích thước [gần đúng] của các khối này có thể được chỉ định bằng cách đặt chunksize thành một số nguyên dương. Trong các lần lặp rất dài, sử dụng giá trị lớn cho Chunksize có thể cải thiện đáng kể hiệu suất so với kích thước mặc định là 1. với
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
4, Chkksize không có hiệu lực.

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

Tắt máy [chờ = true, *, hủy_futures = false][wait=True, *, cancel_futures=False]

Báo hiệu cho người thực thi rằng nó sẽ giải phóng bất kỳ tài nguyên nào mà nó đang sử dụng khi tương lai hiện đang chờ xử lý được thực hiện. Các cuộc gọi đến

with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
8 và
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
4 được thực hiện sau khi tắt máy sẽ tăng
import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']
0.

Nếu chờ đợi là

import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']
1 thì phương pháp này sẽ không trả lại cho đến khi tất cả các tương lai đang chờ xử lý được thực hiện và các tài nguyên được liên kết với người thực thi đã được giải phóng. Nếu chờ đợi là
import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']
2 thì phương thức này sẽ quay lại ngay lập tức và các tài nguyên được liên kết với người thực thi sẽ được giải phóng khi tất cả các tương lai đang chờ xử lý được thực hiện. Bất kể giá trị của sự chờ đợi, toàn bộ chương trình Python sẽ không thoát ra cho đến khi tất cả các tương lai đang chờ xử lý được thực hiện.

Nếu Hủy_Futures là

import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']
1, phương pháp này sẽ hủy bỏ tất cả các tương lai đang chờ xử lý mà người thực thi chưa bắt đầu chạy. Bất kỳ tương lai nào được hoàn thành hoặc chạy won đều bị hủy bỏ, bất kể giá trị của Hủy_Futures.

Nếu cả CECCED_FUTURES và WAIT là

import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']
1, tất cả các tương lai mà người thực thi đã bắt đầu chạy sẽ hoàn thành trước khi phương thức này trả về. Các tương lai còn lại bị hủy bỏ.

Bạn có thể tránh phải gọi phương thức này một cách rõ ràng nếu bạn sử dụng câu lệnh

import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']
5, điều này sẽ tắt
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
6 [chờ như thể
import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']
7 được gọi bằng chờ được đặt thành
import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']
1]:

import shutil
with ThreadPoolExecutor[max_workers=4] as e:
    e.submit[shutil.copy, 'src1.txt', 'dest1.txt']
    e.submit[shutil.copy, 'src2.txt', 'dest2.txt']
    e.submit[shutil.copy, 'src3.txt', 'dest3.txt']
    e.submit[shutil.copy, 'src4.txt', 'dest4.txt']

Đã thay đổi trong phiên bản 3.9: Đã thêm hủy_futures.Added cancel_futures.

ThreadPoolExecutor¶

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
4 là một lớp con
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
6 sử dụng một nhóm các luồng để thực hiện các cuộc gọi không đồng bộ.

Các bế tắc có thể xảy ra khi cuộc gọi có thể gọi được liên quan đến

with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
0 chờ kết quả của một
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
0 khác. Ví dụ:

import time
def wait_on_b[]:
    time.sleep[5]
    print[b.result[]]  # b will never complete because it is waiting on a.
    return 5

def wait_on_a[]:
    time.sleep[5]
    print[a.result[]]  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor[max_workers=2]
a = executor.submit[wait_on_b]
b = executor.submit[wait_on_a]

And:

def wait_on_future[]:
    f = executor.submit[pow, 5, 2]
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print[f.result[]]

executor = ThreadPoolExecutor[max_workers=1]
executor.submit[wait_on_future]

ClassConcienconcurrent.futures.ThreadPoolExecutor[max_workers=None, thread_name_prefix='', initializer=None, initargs=[]]

Một lớp con

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
6 sử dụng một nhóm tại hầu hết các luồng MAX_Workers để thực hiện các cuộc gọi không đồng bộ.

Tất cả các luồng được tính đến

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
4 sẽ được tham gia trước khi trình thông dịch có thể thoát. Lưu ý rằng trình xử lý thoát mà thực hiện điều này được thực thi trước khi bất kỳ trình xử lý thoát nào được thêm bằng
import time
def wait_on_b[]:
    time.sleep[5]
    print[b.result[]]  # b will never complete because it is waiting on a.
    return 5

def wait_on_a[]:
    time.sleep[5]
    print[a.result[]]  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor[max_workers=2]
a = executor.submit[wait_on_b]
b = executor.submit[wait_on_a]
5. Điều này có nghĩa là các trường hợp ngoại lệ trong luồng chính phải được bắt và xử lý để báo hiệu các luồng để thoát ra một cách duyên dáng. Vì lý do này, khuyến nghị rằng
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
4 không được sử dụng cho các nhiệm vụ chạy dài.

Khởi tạo là một cuộc gọi tùy chọn có thể gọi được gọi là bắt đầu mỗi luồng công nhân; initargs là một bộ phận đối số được chuyển cho trình khởi tạo. Nếu khởi tạo tăng một ngoại lệ, tất cả các công việc hiện đang chờ xử lý sẽ tăng

import time
def wait_on_b[]:
    time.sleep[5]
    print[b.result[]]  # b will never complete because it is waiting on a.
    return 5

def wait_on_a[]:
    time.sleep[5]
    print[a.result[]]  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor[max_workers=2]
a = executor.submit[wait_on_b]
b = executor.submit[wait_on_a]
7, cũng như bất kỳ nỗ lực nào để gửi thêm công việc lên nhóm.

Đã thay đổi trong phiên bản 3.5: Nếu MAX_Workers là

with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
5 hoặc không được đưa ra, nó sẽ mặc định với số lượng bộ xử lý trên máy, nhân với
import time
def wait_on_b[]:
    time.sleep[5]
    print[b.result[]]  # b will never complete because it is waiting on a.
    return 5

def wait_on_a[]:
    time.sleep[5]
    print[a.result[]]  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor[max_workers=2]
a = executor.submit[wait_on_b]
b = executor.submit[wait_on_a]
9, giả sử rằng
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
4 thường được sử dụng để chồng chéo I/O thay vì công việc CPU và số lượng công nhân nên cao hơn số lượng công nhân cho
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
5.If max_workers is
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
5 or not given, it will default to the number of processors on the machine, multiplied by
import time
def wait_on_b[]:
    time.sleep[5]
    print[b.result[]]  # b will never complete because it is waiting on a.
    return 5

def wait_on_a[]:
    time.sleep[5]
    print[a.result[]]  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor[max_workers=2]
a = executor.submit[wait_on_b]
b = executor.submit[wait_on_a]
9, assuming that
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
4 is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
5.

Mới trong phiên bản 3.6: Đối số Thread_NAME_PREFIX đã được thêm vào để cho phép người dùng kiểm soát tên

def wait_on_future[]:
    f = executor.submit[pow, 5, 2]
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print[f.result[]]

executor = ThreadPoolExecutor[max_workers=1]
executor.submit[wait_on_future]
2 cho các luồng công nhân được tạo bởi nhóm để gỡ lỗi dễ dàng hơn.The thread_name_prefix argument was added to allow users to control the
def wait_on_future[]:
    f = executor.submit[pow, 5, 2]
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print[f.result[]]

executor = ThreadPoolExecutor[max_workers=1]
executor.submit[wait_on_future]
2 names for worker threads created by the pool for easier debugging.

Đã thay đổi trong phiên bản 3.7: Đã thêm các đối số khởi tạo và khởi đầu.Added the initializer and initargs arguments.

Đã thay đổi trong phiên bản 3.8: Giá trị mặc định của MAX_Workers được thay đổi thành

def wait_on_future[]:
    f = executor.submit[pow, 5, 2]
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print[f.result[]]

executor = ThreadPoolExecutor[max_workers=1]
executor.submit[wait_on_future]
3. Giá trị mặc định này bảo tồn ít nhất 5 công nhân cho các tác vụ ràng buộc I/O. Nó sử dụng tối đa 32 lõi CPU cho các tác vụ ràng buộc CPU giải phóng Gil. Và nó tránh sử dụng các tài nguyên rất lớn ngầm trên các máy nhiều lõi.Default value of max_workers is changed to
def wait_on_future[]:
    f = executor.submit[pow, 5, 2]
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print[f.result[]]

executor = ThreadPoolExecutor[max_workers=1]
executor.submit[wait_on_future]
3. This default value preserves at least 5 workers for I/O bound tasks. It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL. And it avoids using very large resources implicitly on many-core machines.

ThreadPoolExecutor bây giờ tái sử dụng các chủ đề công nhân nhàn rỗi trước khi bắt đầu chủ đề công nhân max_workers.

Ví dụ về ThreadPoolExecutor

import concurrent.futures
import urllib.request

URLS = ['//www.foxnews.com/',
        '//www.cnn.com/',
        '//europe.wsj.com/',
        '//www.bbc.co.uk/',
        '//some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url[url, timeout]:
    with urllib.request.urlopen[url, timeout=timeout] as conn:
        return conn.read[]

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor[max_workers=5] as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit[load_url, url, 60]: url for url in URLS}
    for future in concurrent.futures.as_completed[future_to_url]:
        url = future_to_url[future]
        try:
            data = future.result[]
        except Exception as exc:
            print['%r generated an exception: %s' % [url, exc]]
        else:
            print['%r page is %d bytes' % [url, len[data]]]

ProcessPoolExecutor¶

Lớp

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
5 là một lớp con
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
6 sử dụng một nhóm quy trình để thực hiện các cuộc gọi không đồng bộ.
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
5 sử dụng mô-đun
def wait_on_future[]:
    f = executor.submit[pow, 5, 2]
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print[f.result[]]

executor = ThreadPoolExecutor[max_workers=1]
executor.submit[wait_on_future]
7, cho phép nó bước phụ của khóa phiên dịch toàn cầu nhưng cũng có nghĩa là chỉ các đối tượng có thể chọn có thể được thực thi và trả về.Global Interpreter Lock but also means that only picklable objects can be executed and returned.

Mô -đun

def wait_on_future[]:
    f = executor.submit[pow, 5, 2]
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print[f.result[]]

executor = ThreadPoolExecutor[max_workers=1]
executor.submit[wait_on_future]
8 phải được nhập khẩu bởi các quy trình phụ của công nhân. Điều này có nghĩa là
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
5 sẽ không hoạt động trong trình thông dịch tương tác.

Gọi các phương thức

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
6 hoặc
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
0 từ một cuộc gọi có thể gọi được gửi đến
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
5 sẽ dẫn đến bế tắc.

ClassConcien concurrent.futures.ProcessPoolExecutor[max_workers=None, mp_context=None, initializer=None, initargs=[], max_tasks_per_child=None]

Một lớp con

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

greeting = None

def init[]:
    global greeting
    greeting = 'Hello'

    return None


def main[]:
    with ThreadPoolExecutor[max_workers=1] as executor:
        executor.submit[process]

    return None

def process[]:
    init[]
    print[greeting]

    return None

if __name__ == '__main__':
    main[]
6 thực hiện các cuộc gọi không đồng bộ bằng cách sử dụng một nhóm tại hầu hết các quy trình MAX_Workers. Nếu MAX_Workers là
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
5 hoặc không được đưa ra, nó sẽ mặc định với số lượng bộ xử lý trên máy. Nếu MAX_Workers nhỏ hơn hoặc bằng
import concurrent.futures
import urllib.request

URLS = ['//www.foxnews.com/',
        '//www.cnn.com/',
        '//europe.wsj.com/',
        '//www.bbc.co.uk/',
        '//some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url[url, timeout]:
    with urllib.request.urlopen[url, timeout=timeout] as conn:
        return conn.read[]

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor[max_workers=5] as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit[load_url, url, 60]: url for url in URLS}
    for future in concurrent.futures.as_completed[future_to_url]:
        url = future_to_url[future]
        try:
            data = future.result[]
        except Exception as exc:
            print['%r generated an exception: %s' % [url, exc]]
        else:
            print['%r page is %d bytes' % [url, len[data]]]
5, thì
import concurrent.futures
import urllib.request

URLS = ['//www.foxnews.com/',
        '//www.cnn.com/',
        '//europe.wsj.com/',
        '//www.bbc.co.uk/',
        '//some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url[url, timeout]:
    with urllib.request.urlopen[url, timeout=timeout] as conn:
        return conn.read[]

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor[max_workers=5] as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit[load_url, url, 60]: url for url in URLS}
    for future in concurrent.futures.as_completed[future_to_url]:
        url = future_to_url[future]
        try:
            data = future.result[]
        except Exception as exc:
            print['%r generated an exception: %s' % [url, exc]]
        else:
            print['%r page is %d bytes' % [url, len[data]]]
6 sẽ được nâng lên. Trên Windows, MAX_Workers phải nhỏ hơn hoặc bằng
import concurrent.futures
import urllib.request

URLS = ['//www.foxnews.com/',
        '//www.cnn.com/',
        '//europe.wsj.com/',
        '//www.bbc.co.uk/',
        '//some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url[url, timeout]:
    with urllib.request.urlopen[url, timeout=timeout] as conn:
        return conn.read[]

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor[max_workers=5] as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit[load_url, url, 60]: url for url in URLS}
    for future in concurrent.futures.as_completed[future_to_url]:
        url = future_to_url[future]
        try:
            data = future.result[]
        except Exception as exc:
            print['%r generated an exception: %s' % [url, exc]]
        else:
            print['%r page is %d bytes' % [url, len[data]]]
7. Nếu không phải thì
import concurrent.futures
import urllib.request

URLS = ['//www.foxnews.com/',
        '//www.cnn.com/',
        '//europe.wsj.com/',
        '//www.bbc.co.uk/',
        '//some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url[url, timeout]:
    with urllib.request.urlopen[url, timeout=timeout] as conn:
        return conn.read[]

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor[max_workers=5] as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit[load_url, url, 60]: url for url in URLS}
    for future in concurrent.futures.as_completed[future_to_url]:
        url = future_to_url[future]
        try:
            data = future.result[]
        except Exception as exc:
            print['%r generated an exception: %s' % [url, exc]]
        else:
            print['%r page is %d bytes' % [url, len[data]]]
6 sẽ được nâng lên. Nếu MAX_Workers là
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
5, thì được chọn mặc định sẽ nhiều nhất là
import concurrent.futures
import urllib.request

URLS = ['//www.foxnews.com/',
        '//www.cnn.com/',
        '//europe.wsj.com/',
        '//www.bbc.co.uk/',
        '//some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url[url, timeout]:
    with urllib.request.urlopen[url, timeout=timeout] as conn:
        return conn.read[]

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor[max_workers=5] as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit[load_url, url, 60]: url for url in URLS}
    for future in concurrent.futures.as_completed[future_to_url]:
        url = future_to_url[future]
        try:
            data = future.result[]
        except Exception as exc:
            print['%r generated an exception: %s' % [url, exc]]
        else:
            print['%r page is %d bytes' % [url, len[data]]]
7, ngay cả khi có nhiều bộ xử lý có sẵn. MP_Context có thể là một bối cảnh đa xử lý hoặc không có. Nó sẽ được sử dụng để ra mắt công nhân. Nếu mp_context là
with ThreadPoolExecutor[max_workers=1] as executor:
    future = executor.submit[pow, 323, 1235]
    print[future.result[]]
5 hoặc không được đưa ra, bối cảnh đa xử lý mặc định được sử dụng.

Khởi tạo là một cuộc gọi tùy chọn có thể gọi được khi bắt đầu mỗi quá trình công nhân; initargs là một bộ phận đối số được chuyển cho trình khởi tạo. Nếu khởi tạo tăng một ngoại lệ, tất cả các công việc hiện đang chờ xử lý sẽ tăng

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime[n]:
    if n 

Bài Viết Liên Quan

Chủ Đề