1

I have 3 function and want execute each on new thread using Python

Each function just a math operations.

I need to start each function in each core of process. In Java it's look like:

Thread threadF1 = new Thread(f1);
Thread threadF2 = new Thread(f2);
Thread threadF3 = new Thread (f3);

threadF1.start();
threadF2.start();
threadF3.start();

And if i have 4 cores my program uses 75% of CPU.

I wrote this in Python:

 thread = Thread(target = F1, args=(N,))
 thread.start()

 thread2 = Thread(target = F2, args=(N,))
 thread2.start()

 thread3 = Thread(target = F3, args=(N,))
 thread3.start()

but it uses just 25%. How force working code in Python using 3/4 cores?

A.N.R.I
  • 1,931
  • 2
  • 15
  • 20
  • Note this question: [what is global interpreter lock - GIL](http://stackoverflow.com/questions/1294382/what-is-a-global-interpreter-lock-gil). – Andy Hayden Nov 06 '12 at 23:15

2 Answers2

0

I don't know much python, but try thread.start_new_thread(F1, (N)) for each of your functions.

Here is some documentation I found on the method: thread.start_new_thread


EDIT:

turns out thread was renamed _thread in python 3:

import _thread
_thread.start_new_thread(F1, (N,))
Zaq
  • 1,348
  • 1
  • 11
  • 19
  • I wrote `my_thread = threading.Thread(target=F1(N)) my_thread.setDaemon(True) my_thread.start()` but each function doesn't starting in same time – A.N.R.I Nov 06 '12 at 22:58
  • @A.N.R.I, please edit the question and add that information to the question, where it can be formatted readably. Also explain “doesn't starting in same time” -- do you mean it looks like the threads aren't running concurrently? Do you mean they didn't start at the same nanosecond? Or what? Please reply by editing question – James Waldby - jwpat7 Nov 06 '12 at 23:22
0

In CPython, it is hard to achieve parallelism through threading. This has to do with the Global Interpreter Lock.

One way to work around that is to use the multiprocessing module.

NPE
  • 486,780
  • 108
  • 951
  • 1,012