Why does a Python script only use 6 out of 12 cores?

Abstract: Resolve Python scripts using only half the cores by switching from multi-threading to multi-processing to bypass the Global Interpreter Lock.

Created: 2026-08-27 by
A Python script typically uses only half the available cores because of the Global Interpreter Lock (GIL), which prevents multiple native threads from executing Python bytecodes simultaneously in CPython. To utilize all twelve cores, you must switch from multi-threading to multi-processing or use libraries that release the GIL, such as NumPy or Cython.

The Root Cause: The Global Interpreter Lock

The primary reason your Python application does not scale across all CPU cores is the Global Interpreter Lock (GIL). In standard CPython, the GIL is a mutex that protects access to Python objects, ensuring that only one thread executes Python bytecode at a time. This design simplifies memory management and makes the interpreter single-threaded safe, but it effectively serializes CPU-bound tasks running in separate threads. When you create multiple threads using threading.Thread, the operating system schedules them on different cores. However, the GIL forces these threads to take turns accessing the interpreter. If your task is CPU-intensive, such as heavy mathematical calculations or data processing, the threads spend most of their time waiting for the lock rather than performing useful work. Consequently, you observe high CPU usage on only one or a few cores, while the rest remain idle, regardless of how many threads you spawn. This limitation is specific to CPython. Other implementations like Jython or IronPython do not have a GIL, but they are rarely used in modern production environments. For the vast majority of Python developers, the GIL is a fundamental constraint of the standard library's threading model. Understanding this mechanism is crucial before attempting to optimize performance, as adding more threads will not solve the bottleneck for CPU-bound workloads.

Solution 1: Multi-Processing with the multiprocessing Module

The most robust solution for CPU-bound tasks is to bypass the GIL entirely by using processes instead of threads. Each Python process has its own independent interpreter instance and its own GIL. Therefore, spawning multiple processes allows true parallel execution across all available CPU cores. You can achieve this using the built-in multiprocessing module. Instead of creating threads, you create processes. The overhead of inter-process communication is higher than thread communication, but for CPU-heavy tasks, the benefit of parallel execution outweighs this cost. Here is a basic example of how to structure your code:
import multiprocessing
import os

def worker():
    # Perform CPU-intensive work here
    result = sum(i * i for i in range(1000000))
    print(f"Worker {os.getpid()} finished")

if __name__ == "__main__":
    # Create a pool of workers equal to the number of cores
    num_cores = multiprocessing.cpu_count()
    with multiprocessing.Pool(processes=num_cores) as pool:
        results = pool.map(worker, range(num_cores))
In this example, multiprocessing.cpu_count() detects the number of logical processors, which should return 12 for your system. The Pool object manages a fixed number of worker processes. When you call pool.map, it distributes the workload evenly among these processes. Each process runs independently, allowing all 12 cores to be utilized simultaneously. For more complex scenarios where you need fine-grained control over process creation and communication, you can use Process objects directly along with Queue or Pipe for data exchange. However, for most bulk processing tasks, the Pool interface provides the best balance of simplicity and performance.

Solution 2: Libraries That Release the GIL

Not all Python code is affected by the GIL. Many popular scientific computing libraries, such as NumPy, Pandas, and SciPy, are implemented in C or Fortran. These libraries release the GIL during long-running computational operations. This means that if your Python script primarily delegates work to these libraries, you may see better utilization of multiple cores even without explicit multi-processing. However, this behavior is not guaranteed for all functions within these libraries. You must check the documentation for specific functions to see if they release the GIL. For custom C extensions, you can explicitly release the GIL using the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros in C code. If you are writing performance-critical code, consider using tools like Cython or Numba. Cython allows you to write C-like code in Python and compile it, giving you precise control over the GIL. Numba can JIT-compile Python functions to machine code, often releasing the GIL automatically for numerical loops. For general-purpose parallelism beyond simple function mapping, consider using distributed computing frameworks like Ray or Dask. These tools provide higher-level abstractions for parallel computing and can handle larger-than-memory datasets efficiently. They manage process distribution and data serialization automatically, reducing the boilerplate code required for manual multi-processing.

Diagnostics and Verification

Before implementing changes, verify that your system actually has 12 accessible cores. Use nproc on Linux or PowerShell’s (Get-CimInstance Win32_Processor).NumberOfLogicalProcessors on Windows. Sometimes, virtualization settings or power management profiles limit the number of active cores. Use monitoring tools like htop on Linux or Task Manager on Windows to observe CPU usage per core. If you see spikes on only 6 cores, it confirms the GIL bottleneck. After switching to multi-processing, monitor again to ensure all 12 cores show activity during execution. How to Run Any GGUF Model Using Transformers or Any Other Library discusses similar optimization challenges in AI workloads, where efficient resource utilization is critical.

Frequently Asked Questions

Does the GIL affect I/O-bound tasks?

No, the GIL does not significantly impact I/O-bound tasks like reading files or making network requests. During I/O operations, threads release the GIL, allowing other threads to run. Therefore, multi-threading is still effective for applications that spend most of their time waiting for external resources.

Can I remove the GIL from Python?

You cannot remove the GIL from standard CPython without rebuilding the interpreter with experimental patches. While there are ongoing projects to make the GIL optional or remove it entirely, no stable release exists yet. For now, using multi-processing is the standard workaround.

Is multi-processing slower than multi-threading?

Multi-processing has higher overhead due to process creation and inter-process communication costs. However, for CPU-bound tasks, the speedup from parallel execution far outweighs this overhead. For I/O-bound tasks, multi-threading remains faster due to lower context-switching costs.

How do I share data between processes?

You can share data using multiprocessing.Queue, multiprocessing.Pipe, or shared memory objects like Array and Value. Avoid sharing mutable state directly; instead, pass data through queues or use read-only shared memory for performance.

What happens if I use both threads and processes?

You can combine both approaches, but it adds complexity. Typically, you use processes for CPU-bound parallelism and threads for concurrent I/O within each process. Ensure that any threading within a process does not contend heavily on the GIL for CPU work.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More