Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I execute two functions at the same time?

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.

like image 861
Dutchman Avatar asked Nov 28 '11 17:11

Dutchman


People also ask

Can you run two functions at the same time?

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.

Can we run multiple functions concurrently in C?

If your C program uses MTF, the main task program and several different computationally-independent parallel functions can run concurrently.

Can Python run two functions in parallel?

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.


1 Answers

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.

like image 89
Adam Maras Avatar answered Sep 30 '22 04:09

Adam Maras