I'm assuming there's no easier way to do this. Is thread locking really automatic? Am I misreading the documentation?

from threading import Thread

make_thread = lambda fn, *args: Thread(None, fn, None, args).start()

def my_fn(*args):
    for arg in args: print (arg)

make_thread(my_fn, "toaster", "ovens")

Recommended Answers

All 6 Replies

I am not quite sure in general if exists any automatic locking mechanism, but in this case, as far as I can see there is no locking, not automatic nor manual.

Yes, that is approximately the usual way to create Python threads.

Why do you need locking? Best to be a bit more specific about your question.

Why do you need locking?

I don't, particularly. Rather I wanted to know if there's an automatic form of locking. I've discovered only single-step operations don't require a lock.

lock = Lock()
lock.acquire()
# ...
lock.release()

Of extending Thread or passing Thread a callable, what is generally better?

I usually pass a callable, because it is less typing. I doubt there is any reason to extend Thread... unless you have a reason to extend Thread... Most of the reasons I can think of off the top of my head can be handled by decorating the callable (or just adding code to it directly).

If you are new to Python threads, be aware that they are often not very efficient (better conceptually, maybe, but probably not very fast). See, for instance http://www.grouplens.org/node/244

Agree it might be better, depending on what you really need. Threads and processes are similar enough that early Linuxen used "light weight processes" to do threading (and for all I know, maybe they still do); do obviously Python can do something similar.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.