cpp_code = """ #include <iostream> #include <thread> #include <vector> #include <atomic> const int INCREMENTS_PER_THREAD = 100000; //int counter = 0; // 这行是错的 __________ void increment() { for (int i = 0; i < INCREMENTS_PER_THREAD; ++i) { counter++; // 非原子操作 } } int main() { int num_threads; std::cin >> num_threads; std::vector<std::thread> threads; // 创建多个线程同时对 counter 进行递增操作 for (int i = 0; i < num_threads; ++i) { threads.emplace_back(increment); } // 等待所有线程完成 for (auto& th : threads) { th.join(); } // 输出最终的 counter 值 std::cout << counter << std::endl; return 0; } """ import os import sys def compile_and_run_cpp(cpp_code): cpp_filename = "main.cpp" executable = "./a.out" with open(cpp_filename, 'w') as file: file.write(cpp_code) compile_command = f"g++ {cpp_filename} -o {executable}" compile_result = os.system(compile_command) if compile_result != 0: print(f"Compile Error: Compilation failed", file=sys.stderr) sys.exit(1) run_command = f"{executable}" run_result = os.system(run_command) if run_result != 0: print(f"Runtime Error: Execution failed", file=sys.stderr) sys.exit(1) if __name__ == "__main__": compile_and_run_cpp(cpp_code)