我有一个耗时的python任务需要优化,我打算在子线程中计算结果,计算完成后再将数据返回给主线程,要求在子线程执行期间主线程不卡死
Jump to turn (9)
- User
我有一个耗时的python任务需要优化,我打算在子线程中计算结果,计算完成后再将数据返回给主线程,要求在子线程执行期间主线程不卡死
- Assistant
你可以使用Python中的多线程模块来解决这个问题。多线程允许您同时运行多个线程,并在完成任务后返回结果。
以下是一个简单的示例代码,它使用多线程模块来计算大量数字的平方并返回结果:
codeimport threading def calculate_square(numbers): print("Calculating squares...") result = [] for n in numbers: result.append(n * n) print("Calculation complete.") return result if __name__ == "__main__": numbers = [2, 3, 4, 5, 6, 7] # Create a new thread and pass the calculate_square function as an argument t = threading.Thread(target=calculate_square, args=(numbers,)) # Start the thread t.start() # Continue to do other things in the main thread # Wait for the thread to complete and retrieve the result t.join() result = t.result print(result)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.