Python Multithreading: Calculate Array Sum with User-Defined Threads
Here is the modified code with threading and user input for the number of threads:
import threading
def calculate_sum(start, end, arr, result):
partial_sum = 0
for i in range(start, end):
partial_sum += arr[i]
result.append(partial_sum)
if __name__ == "__main__":
arr = [i for i in range(1, 10000001)]
result = []
num_threads = int(input('Enter the number of threads to use: '))
chunk_size = len(arr) // num_threads
threads = []
for i in range(num_threads):
start = i * chunk_size
end = start + chunk_size if i != num_threads - 1 else len(arr)
thread = threading.Thread(target=calculate_sum, args=(start, end, arr, result))
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
total_sum = sum(result)
print('Total sum:', total_sum)
The user is prompted to enter the number of threads they want to use. The program then divides the array into chunks based on the number of threads and creates a separate thread for each chunk. Each thread calculates the partial sum for its chunk and appends it to the 'result' list. After all threads have completed, the program sums up the partial sums in the 'result' list to obtain the total sum.
原文地址: https://www.cveoy.top/t/topic/mMMJ 著作权归作者所有。请勿转载和采集!