Question

I'm writing a C program that looks like this:

for (int i=0;i<n;i++){
    [makes new file for i: i.txt]
    [runs a long and intensive computation]
    [writes to i.txt]
    [closes i.txt]}

where n is some large number. Obviously, several iterations at once could be run in parallel, as they do not depend on each other. I have eight cores on my processor, so it seems that I would want my program to distribute the iterations on the eight cores, so it runs as quickly as possible. This means I would want the program to be multi-threaded.

My question is whether I would need to manually multi-thread this process in C, or whether multi-threading is done automatically on some level. I'm compiling with GCC and I know that GCC optimizes well, but I don't know whether it automatically multithreads. I also don't know whether my OS (Debian Linux) might not automatically distribute the program onto all eight cores of my processor. If not, is there a way I can get it to multi-thread without having to actually write multi-threading code in C?

Était-ce utile?

La solution

You can multithread it manually if you want, or you can use libraries and tools that take over as much or as little of the responsibility as you like. OpenMP is definitely worth looking at.

Autres conseils

The simple answer is no: GCC does no automatic multithreading in itself. Multithreading is defined in layers strictly above C, so GCC doing that would be kind of a layering violation.

That being said, there are lots of libraries that make the job easier (not that manually multithreading your particular case is a lot of work to begin with), and some of them integrate more tightly at the language level. OpenMP has been mentioned by others.

You may also consider the new additions to the C11 standard regarding multithreading applications

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top