Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiprocessing with threading?

when I trying to make my script multi-threading,

I've found out multiprocessing,

I wonder if there is a way to make multiprocessing work with threading?

  • cpu 1 -> 3 threads(worker A,B,C)
  • cpu 2 -> 3 threads(worker D,E,F)
  • ...

Im trying to do it myself but I hit so much problems.

is there a way to make those two work together?

like image 324
at th3burger91 Avatar asked Jul 16 '17 14:07

at th3burger91


People also ask

Can you combine multiprocessing and multithreading?

If you combine multiprocessing with multithreading in fork "start methods", you need to ensure your parent process "fork safe". The fork() only copy the calling thread, it causes deadlock easily.

Should I use threading or multiprocessing?

If your program is IO-bound, both multithreading and multiprocessing in Python will work smoothly. However, If the code is CPU-bound and your machine has multiple cores, multiprocessing would be a better choice.

Is threading faster than multiprocessing?

Threads are faster to start than processes and also faster in task-switching. All Threads share a process memory pool that is very beneficial. Takes lesser time to create a new thread in the existing process than a new process.

Does Python multiprocessing use multiple threads?

Multiprocessing is a technique where parallelism in its truest form is achieved. Multiple processes are run across multiple CPU cores, which do not share the resources among them. Each process can have many threads running in its own memory space.


1 Answers

You can generate a number of Processes, and then spawn Threads from inside them. Each Process can handle almost anything the standard interpreter thread can handle, so there's nothing stopping you from creating new Threads or even new Processes within each Process. As a minimal example:

def foo():
    print("Thread Executing!")

def bar():
    threads = []
    for _ in range(3): # each Process creates a number of new Threads
        thread = threading.Thread(target=foo) 
        threads.append(thread)
        thread.start()
    for thread in threads:
        thread.join()

if __name__ == "__main__": 
    processes = []
    for _ in range(3):
        p = multiprocessing.Process(target=bar) # create a new Process
        p.start()
        processes.append(p)
    for process in processes:
        process.join()

Communication between threads can be handled within each Process, and communication between the Processes can be handled at the root interpreter level using Queues or Manager objects.

like image 67
JAustin Avatar answered Oct 12 '22 02:10

JAustin