Home > OS >  Threading with switch_locks doesn't modify dictionary, or throws common errors (RuntimeError, e
Threading with switch_locks doesn't modify dictionary, or throws common errors (RuntimeError, e

Time:12-05

I wrote a simple program to help me learn threading, working with dictionaries, and using switch_locks.

import threading
import random, string
from threading import Lock
import time

eve = True
switch_lock = Lock()


# produce random words
def wordfeed():
    global wordfeed
    wordfeed = ''.join(random.choices(string.ascii_lowercase, k=5))
    x2 = threading.Thread(target=collector())
    x2.start


# collect random words
def collector():
    while eve == True:
        global a, z, wordfeed
        z = random.randint(0, 20)
# creation of buffer
        o=0
        if o==0:
            a={f'{wordfeed}': ''}
            o = o 1
        elif o>0:
# APPEND KEY-VALUE PAIRS!   
            switch_lock.acquire()
            a.add[f'{wordfeed}', f'{z}']
            switch_lock.release()
            print(a)
        x3 = threading.Thread(target=processor())
        x3.start

#iterate through and del highest values of keys
def processor():
    while eve == True:
        global a, z, wordfeed
        switch_lock.acquire()
        for key in a:
            print(a)
            if z > 18:  
                print(a)
                del a[f'{wordfeed}']
        switch_lock.release()       

wordfeed()

Output is either same key: value (random key, empty value), or the RuntimeError.

#s specify what I'm trying to do at each step. I can't get my mind around why I can't get this program to append and print new key:value pair, endlessly expanding the dictionary (and at the end cutting the highest values for certain pairs?

What am I not seeing here?

CodePudding user response:

  1. This will obviously never be false:
o=0
if o==0:

You are resetting o to 0 every loop, you need to initialize it outside the loop.

  1. dictionaries don't have a add() method.

a.add[f'{wordfeed}', f'{z}']

It's not clear what you are trying to do, even a[f'{wordfeed}'] = f'{z}' wouldn't work since you are just overwriting the same key over and over since wordfeed never changes.

  1. you never actually multithread,
x2 = threading.Thread(target=collector())
x2.start

should be

x2 = threading.Thread(target=collector)
x2.start()
x2.join()

otherwise, it means that it will pass the result of collector() to Thread() but that means it will first be evaluated by the main thread. What you want is to pass the function collector as a parameter so the other thread x2 will do the task.

Here the main thread just calls collector(), which calls processor() which loops forever since eve is always True.

Also x2.start is a method and needs to be called. And if you don't wait for your thread to finish with join() the program will just end immediately and do nothing.

Honestly, that's just the tip of the iceberg. Fixing this code will teach you a lot.

  • Related