1

I have character array just like 'XOOOXOX' and I need to rearrange this array-like 'XXXOOOO'. I can create simple python code for this. But I am find a way to do it using multithreading. Can anyone help me to do this?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

3

This might be a funny answer, but the question was about using threads. So I just created a dummy threading work. This might won't show a performance gain at all:

import random
import threading

a = random.choices(['X', 'O'], k=10000)
a = ''.join(a)

print(a.count('X'), a.count('O'))

thread_count = 4
lock = threading.Lock()

x_count = 0
o_count = 0


def chunk_it(seq, num):
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out


def d(i):
    global x_count
    global o_count

    data_part = chunk_it(a, thread_count)[i]

    with lock:
        x_count += data_part.count('X')
        o_count += data_part.count('O')


ts = []
for i in range(thread_count):
    t = threading.Thread(target=d, args=(i, ))
    ts.append(t)

for t in ts:
    t.start()

for t in ts:
    t.join()

a = 'X' * x_count + 'O' * o_count
print(a)
print(a.count('X'), a.count('O'))

You can copy and try it.

This demo meant to show using a relatively lower level threading api.

Concurrency in python led by several modules: threading, multiprocessing, concurrent.futures, asyncio and so. You definitely might want to check out these. Diving right into official documentations might be difficult for this concept. You should read from others and practice.

emremrah
  • 1,733
  • 13
  • 19
  • You're missing a few characters since you're doing a floor divide for the part size. Secondly, your locking is wrong. Could you please fix it? – Balaji Ambresh Jun 02 '20 at 18:16
  • Yes, I'm aware of the character missing situation. I just wanted to show the concept. I fixed the locking issue, thank you for pointing it out. – emremrah Jun 02 '20 at 18:20
  • Okay, the issue was with the total length of the array. If it couldn't divide by number of threads, this situation occurs. Just fixed it by adding a function, `chunkIt`, to divide array equally into total length of threads. Credidts for the function: https://stackoverflow.com/a/2130035/6402099 – emremrah Jun 02 '20 at 18:31