Ephemera
Ephemera

Reputation: 8970

Creating threads on a single-core processor

I am making an application in C that depends on asynchronous method calls. In my best efforts thus far to make it cross platform I am currently implementing code that looks like this:

#ifdef TARGET_WINDOWS
//Windows threading API
#else
//pthreads API
#endif

I appreciate there is probably a better way to do that but that is not the point of my question. My question is, what will happen to the program on a single-core processor? Will the threads still execute asynchronously (interleaved instructions perhaps), or am I stuck with single-thread execution only on single-core CPUs?

Upvotes: 0

Views: 1983

Answers (3)

Science_Fiction
Science_Fiction

Reputation: 3433

At the end of the day a single core can only run one thread at a time. The thread scheduler will interrupt the running thread and give another thread the chance to run for the specified quantum.

Now what happens exactly is up to the OS. But should all your work be CPU bound, maybe some intensive calculations then the overall performance may in fact degrade with more threads due to the cost of context switching. But if you are waiting on I/O for example, the OS can schedule another thread to run in the meantime to make use of CPU.

Upvotes: 2

Tudor
Tudor

Reputation: 62439

Threads on a single core CPU each get tiny timeslices from the OS in turn, depending on a few factors such as static and dynamic priority, the type of process they're running in, etc. Point is, they will run in a parallel(ish) fashion (concurrently in fact) by interleaving their executions on the single CPU.

Upvotes: 0

the_ien
the_ien

Reputation: 84

The threads will execute concurrently, even on a single core. This is because of preemptive scheduling, which means that the OS will pause threads to let other threads run.

This is true for all the common desktop OSes. However, embedded/"real time"-OSes might be different.

Upvotes: 1

Related Questions