Python Forum

Full Version: Locks in Multithreading
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Pythoners,

I am having trouble with some multithreading.
My goal is it to read a given list and start a thread for each element of this list, in this thread i want to sort the elements into a new empty list.

my problem is, that no matter how i set up my locks, the sorting works for the first few elements, but after that numbers, which schuld be in the middle in the list, just get appended to the end of the list

the code below for example gives me for s1 [3, 5, 7, 9, 122, 222, 213, 210]
What did i do wrong, how do i know where to put the locks ?

import threading
def parsort(v,s,lock):
    i=0
    if s==[]:
        s.append(v)
    else:
        while i < len(s):
            if s[i] > v and not v in s:
                print(v)
                s.insert(i,v)
            elif not v in s:
                s.append(v)
            i=i+1

#Mainprogramm
s1=[]
l=[5,3,7,9,122,222,213,210]
lock=threading.RLock()

for  i in l :
    sort=threading.Thread(target=parsort,args=(i,s1,lock))
    sort.start()
    for j in l:
        sort.join()


print(s1)