7

Code to add and delete values in a list are operations performed in different threads.

using these global variables in multi-threading:

from threading import Thread
import time

a=[]
i = 0
j = 0

function for thread1:

def val_in():
    while 1:
        a.append(raw_input())
        print "%s value at %d: %d added" % ( time.ctime(time.time()), i ,int(a[i])) // line 14
        i+=1

function for thread 2:

def val_out():
    while 1:
        time.sleep(5)
        try:
            print "%s value at %d: %d deleted" % (time.ctime(time.time()), j, int(a.pop(j)))
            i-=1
        except:
            print"no values lefts"
        time.sleep(2)

defining and starting threads:

t = Thread(target = val_in)
t1 = Thread(target= val_out)
t.start()
t1.start()

Now when input is given as 1, it should be added to the list a, but there is an error:

Error: Exception in thread Thread-1:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
   self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
   self.__target(*self.__args, **self.__kwargs)
  File "/Users/dhiraj.agarwal/Documents/workspace/try3/multithread.py", line 14, in val_in
UnboundLocalError: local variable 'i' referenced before assignment

2 Answers 2

14

You should tell python that i is global:

def val_in():
    global i
    ...

def val_out():
    global i
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

@DhirajAgarwal, if you are happy with this answer, please accept it, or at least vote it up. welcome! :-)
0

This is an issue with the scope of the variable. You might used local variable in the thread for different methods. If that the case then you have to make the variable as global.

def val_in():
    global i  # add this line
    while 1:
        a.append(raw_input())
        print "%s value at %d: %d added" % ( time.ctime(time.time()), i ,int(a[i]))
        i+=1

def val_out():
    global i  # add this line
    while 1:
        time.sleep(5)
        try:
            print "%s value at %d: %d deleted" % (time.ctime(time.time()), j, int(a.pop(j)))
            i-=1
        except:
            print"no values lefts"
        time.sleep(2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.