tungns
tungns

Reputation: 96

Threads don't run simultaneously

I have a simple multi-threading code in which some threads put items to queue and some threads get items from queue: https://repl.it/@chuoi123/simpleThreading

Full code if you don't want to visit link above:

import threading
import queue
import time

def PutWorker(maxValue):
    global item
    while True:
        with putLock:
            if item > maxValue:
                break
            q.put(item)
            print('Added item ' + str(item))
            item += 1
        time.sleep(0.5)

def GetWorker():
    while True:
        item = q.get()
        if item is None:
            break
        with getLock:
            print('Deleted item ' + str(item))
        q.task_done()
        time.sleep(1)

## main process from here
q = queue.Queue()
threads = []
putLock = threading.Lock()
getLock = threading.Lock()
item = 1

while True:
    try:
        numValue = int(input('Number of items in queue: '))
        numThreadsGet = int(input('Number of getting threads: '))
        numThreadsPut = int(input('Number of putting threads: '))
        break
    except:
        print('Input must be ingeter.')

for i in range(numThreadsPut):
    t = threading.Thread(target=PutWorker(numValue),daemon = True)
    t.start()
    threads.append(t)

for i in range(numThreadsGet):
    t = threading.Thread(target=GetWorker,daemon = True)
    t.start()
    threads.append(t)

My problem is putting threads and getting threads don't run simultaneously, so one type run after another base in their order in code. The result of current code:

Added item 1
Added item 2
Added item 3
Added item 4
Added item 5
...
Deleted item 1
Deleted item 2
Deleted item 3
Deleted item 4
Deleted item 5
...

And I want result like this:

Added item 1
Added item 2
Deleted item 1
Added item 3
Deleted item 2
Added item 4
Deleted item 3
Added item 5
Deleted item 4
Deleted item 5
...

Why this happened and What I can do for archive my goal?

Edit: after try solution in @user68014's answer, I found another way is remove parameter from def PutWorker() and simple using global variable there like item.

Upvotes: 0

Views: 64

Answers (1)

user68014
user68014

Reputation: 146

The problem is with this line:

t = threading.Thread(target=PutWorker(numValue),daemon = True)

You're actually calling PutWorker to get the target to Thread. So it's all happening before the thread is actually created. You should be passing in the function itself.

So something like:

t = threading.Thread(target=PutWorker, ...

No arguments, no call, it's just a function (which Thread will call to start the thread)

Since it has a parameter, you need to "Curry" that in. I'd do it like this:

from functools import partial

...

t = threading.Thread(target=partial(PutWorker, numValue), ...

Upvotes: 1

Related Questions