Skip to content

Instantly share code, notes, and snippets.

@ixtiyoruz
Created November 22, 2021 14:05
Show Gist options
  • Save ixtiyoruz/00d3cf825ea0981f215a90c86aed63a2 to your computer and use it in GitHub Desktop.
Save ixtiyoruz/00d3cf825ea0981f215a90c86aed63a2 to your computer and use it in GitHub Desktop.
multithreading vs multiprocessing
@ixtiyoruz
Copy link
Author

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 22 22:47:32 2021

@author: Challenger
"""

from threading import Thread
import os
import math
import time
import cv2

def calc():
    for i in range(0, 10):
        path = "C:/Users/Challenger/Documents/projects/leetcode/new.png"
        cv2.imread(path, -1)
threads = []

for i in range(os.cpu_count()):
	print('registering thread %d' % i)
	threads.append(Thread(target=calc))
start = time.time()
for thread in threads:
	thread.start()


for thread in threads:
	thread.join()
end= time.time()-start
print(f"finished in {end}")

@ixtiyoruz
Copy link
Author

This runs thread inside a process


import cv2
import time
import os
import multiprocessing
import time
from threading import Thread

# run from video
class TestMP(multiprocessing.Process):
    def __init__(self, send,  recv, data_stream):        
        multiprocessing.Process.__init__(self)        
        self.send = send
        self.recv = recv
        # self.queue = data_stream
        self.queue = []
        
         # does not work
        # self.locker = multiprocessing.Lock()
    def run(self):        
        self.thread = Thread(target=self.run_thread)
        self.thread.start()
        while(True):
            # counter = self.recv.recv()
            if(len(self.queue) > 0):
                counter = self.queue.pop(0)
                print("counter mp: ", counter)
                time.sleep(0.1)

    def run_thread(self):
        count = 0
        while(True):
            count +=1
            # self.send.send(count)
            self.queue.append(count)
            print("counter thread: ", count)
            time.sleep(0.1)

if __name__ == "__main__":
    recv, send = multiprocessing.Pipe(False)
    data_stream = multiprocessing.Queue()
    testmp = TestMP(send, recv, data_stream)
    testmp.start()
    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment