I am new to programming. I know that a computer executes instructions in the order they are given.
I'm learning C and I wrote this:
#include <stdlib.h>
#include <stdio.h>
int comp(const char *a, const char *b) {
return *a - *b;
}
int main() {
char str[] = "Hello, world! I'm learning C and it's awesome!";
qsort(str, sizeof(str) - 1, sizeof(char), comp); // -1 because of NUL-terminator.
puts(str);
return 0;
}
However, when I want to sort multiple very large arrays, this can take a while. My computer has multiple processing cores so I want to take advantage of that. Is that possible? Can code run in parallel and how would I do that?
P.S. I know I have to profile the code before optimizing it, but for now assume this is a very slow operation.
There are three approaches to running two functions at the same time. They are threading, multiprocessing, and asyncio modules. Let's understand each of the three methods of concurrently running two functions with the help of an example.
If your C program uses MTF, the main task program and several different computationally-independent parallel functions can run concurrently.
One common way to run functions in parallel with Python is to use the multiprocessing module which is powerful, it has many options to configure and a lot of things to tweak.
What you're looking for is called threading. There are a great many resources and tutorials out there on the Internet to get you started with parallelizing code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With