Are python functions threadsafe? (Particularly this one?)
Before answering, please understand I do NOT want you to do the work for me. I would rather appreciate a worded answer as to why my (possibly theoretical) problem exists, and an explanation of the process to go about fixing it. I find it harder to learn properly when someone just does the work for me. Thank you in advance.
I have this function: It does exactly what it looks like it's doing. It is using the html from a page which contains a facebook ID and returning the ID once found.
def getID(data): #Find an ID from HTML input. data = str(data) appstring = 'http://apps.facebook.com/castle_age/keep.php?user=' #We're gonna find this in the html. appstr_start_pos = data.find(appstring) #Tell us where we found it oh mighty one! if appstr_start_pos != -1: #If we find it. begin_ID_pos = appstr_start_pos + len(appstring) end_ID_pos = data.find('"', begin_ID_pos) #Find the end quote, that'll be the end of our ID string. our_ID = data[begin_ID_pos:end_ID_pos] return our_ID
Right now I do not have it packaged in one of my classes which uses the thread.Threading method, but I am still calling it regularly. My code right now is only running one thread, and it's possible that I might need to call this function from another threaded class; is this possible? If not, how can I use this function between threaded classes?
A more simple form of the question: If I call this function from a multi-threaded environment, will I have problems, or do I need to move it into its own class? Is there a way to keep the function available between 2 different threaded objects (if so what's the easiest way)?
Here is the full code: http://pastebin.com/txH8PvL3 -- Please keep in mind that it is a WIP, as practice for learning threading...
A more simple form of the question: If I call this function from a multi-threaded environment, will I have problems,
Yes it is thread-safe from what I can tell
or do I need to move it into its own class?
Thread safety has nothing to do with classes: it has to do with shared state. If threads share state, provisions must be made to access/mutate this state in a thread-safe manner i.e. using locks.
Builtin functions len(), str() that is used in your function can be monkey-patched in other threads.
It is not so easy because every get*() function could use caches. So every call could leat into data changes. -> problem