How to change the order in which it is printed in a program with MultiHilos?

1

Paralleled program, which uses n independent threads to process a given list of m requests. The threads take the requests in the order they are given in the entry. If there is a free thread, it immediately takes the next request from the list. However, if a thread has already begun to process a request, it can not be interrupted or stopped until the end of processing. If several threads try to take requests from the list simultaneously, the thread with a lower index will be the one that attends it. For each request you know the exact time that any thread will take to process it.

Determine the thread that processes each of the requests, and the time it will begin to do so. Assume that the initial time is 0.

Entry:

The first line is a T number that represents the number of test cases. Below is the description of each case.

The first line of each case contains 2 numbers, n and m , which represent the number of threads and the number of requests, respectively. Then follow a line with m numbers, where the ith number denotes the time it takes to process the request i (by any thread).

Exit:

For each case, print m lines. Each line must have two numbers separated by a space: the thread that processes the i-th request and the time it begins to process it.

This is my code:

import threading
from queue import Queue
import time
print_lock=threading.Lock()

def job(request,thread):
    time.sleep(0.5)
    with print_lock:
        print(thread,request)

def worker(count):
    """Funtion that executes the thread"""
    timeOfExecution=0
    while True:
        request=queue.get()
        job(timeOfExecution,count)
        timeOfExecution+=request
        queue.task_done()


T = int(input())

for case in range(T):
    N, M = map(int, input().split(' '))
    if 1<=N and N<=100000 and 1<=M and M<=100000:
        requests= list(map(int,input().split(' ')))
        queue=Queue()
        for i in requests:
            queue.put(i)
        for i in range(N):
            t = threading.Thread(target=worker, args=(i,))
            t.daemon=True
            t.start()
        queue.join()

For the test case:

  

1
     4 20
     1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

I get:

  

1 0
     2 0
     0 0
     3 0
     0 1
     1 1
     2 1
     3 1
     1 2
     2 2
     0 2
     3 2
     2 3
     0 3
     1 3
     3 3
     0 4
     1 4
     2 4
     3 4

But what should I get out is this:

  

0 0
  1 0
  2 0
  3 0
  0 1
  1 1
  2 1
  3 1
  0 2
  1 2
  2 2
  3 2
  0 3
  1 3
  2 3
  3 3
  0 4
  1 4
  2 4
  3 4

The result is the correct one but it prints it in a different order. Does anyone know why this is happening?

Thank you very much

    
asked by MNoguera 15.04.2017 в 23:44
source

0 answers