0

I search a way to transform this kind of code from multiprocessing into multithreading:

import multiprocessing
import random
import time 

FIND = 50
MAX_COUNT = 100000
INTERVAL = range(10)

queue = multiprocessing.Queue(maxsize=1)

def find(process, initial):
    succ = False
    while succ == False:
        start=initial
        while(start <= MAX_COUNT):
            if(FIND == start):
                queue.put(f"Found: {process}, start: {initial}")
                break;
            i = random.choice(INTERVAL)
            start = start + i
            print(process, start)

processes = []
manager = multiprocessing.Manager()
for i in range(5):
    process = multiprocessing.Process(target=find, args=(f'computer_{i}', i))
    processes.append(process)
    process.start()

ret = queue.get()
for i in range(5):
    process = processes[i]
    process.terminate()
    print(f'terminated {i}')

print(ret)

The way it works is it starts multiple processes and after the first process finished the function find isn't needed anymore. I tried to transform it in that way, but unfortunately the terminate function is not usable:

import _thread as thread
import queue
import random
import time 

FIND = 50
MAX_COUNT = 100000
INTERVAL = range(10)

qu = queue.Queue(maxsize=1)

def find(process, initial):
    succ = False
    while succ == False:
        start=initial
        while(start <= MAX_COUNT):
            if(FIND == start):
                qu.put(f"Found: {process}, start: {initial}")
                break;
            i = random.choice(INTERVAL)
            start = start + i
            print(process, start)

threads = []
for i in range(5):
    th = thread.start_new_thread(find, (f'computer_{i}', i))
    threads.append(th)

ret = qu.get()
for i in range(5):
    th = threads[i]
    th.terminate()
    print(f'terminated {i}')

print(ret)

How can I get some termination of threads?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Martin Kunze
  • 995
  • 6
  • 16

1 Answers1

-1

Try:

for id, thread in threading._active.items():
      types.pythonapi.PyThreadState_SetAsyncExc(id, ctypes.py_object(SystemExit))
Nir Elbaz
  • 556
  • 4
  • 19
  • Be aware that this will kill any and all threads. This includes threads spawned by other modules/functions/libraries as well as the main thread. – MisterMiyagi Feb 22 '22 at 12:23
  • Agreed, I was under the impression that what he was looking for , if not he need to save the id every time he create a new thread – Nir Elbaz Feb 22 '22 at 12:25