Search code examples
cmultithreadingpthreadscpu

How many threads can I create inside a C program and how does it relate to the number of threads my CPU has?


My CPU is an i5-8400, which has 6 cores and 6 threads. What does this mean? Initially, I thought it meant that I had 6 threads available per core, which totals 36 threads.

Say I'm making a C program, where I create pthreads, does that mean I can only have 6 threads in that program, as its process will run on a single CPU core? If that's the case, what would happen if I tried creating a seventh thread?

When I go to task manager (windows), I see thousands of threads:

enter image description here

, which means my understanding was wrong.

So my questions are:

  1. How does my CPU number of threads relate to how many threads I can create in a process, i.e., say I create a C program; how many threads can I create in its process?
  2. What happens if I try to create a thread, and there are no more threads available?

Solution

  • Intel CPU has cores an multiple execution unit per core. A mainboard can have many CPU.

    For example, my system has 2 Intel Xeon E5620 processors. Each Xeon E5620 has 4 cores and each core can execute 2 threads (That is the hyperthreading feature). On my system, a total of 2x4x2=16 threads can be execute really simultaneously).

    The difference between the number of threads and the number of cores exists because CPU has incomplete core which is able to execute multiple threads but less performing than a complete core. To say it otherwise, it is faster to have 8 cores single thread than 4 cores each double thread.

    When we talk about the number of thread in CPU context, it means that you can have so much thread really executing in parallel. While you look at the task manager, you see the total number of thread objects in the system. At a given moment, most of them are sleeping (for example waiting for I/O or a mutex,...) only the number of thread given for the CPU times the number of CPU can be really executing instructions.

    If you create more threads than is available in the available CPU, then part of them are simply waiting for their turn to execute. A CPU thread execute one after the other the existing threads. Actually the operating system has a scheduler that determine which thread is ready to run or not.

    Interesting readings: