473,605 Members | 2,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

threading, how to?

Hi,

I am trying to understand how to use threading in Python. I get
threading as a concept, but not the implementation.

In order to start threading, do you call it as a separate function,
which will then be applied to the rest of the code (functions) or do
you open threading in each function. This all can probably be answered
by 'How python threads different functions'?

Hope if somebody can drop me a few lines. I've been trying with
different tutorials, but still do not understand.

Cheers,

Stevan

Apr 21 '06 #1
9 2168
"akrapus" <ak****@gmail.c om> writes:
Hi,

I am trying to understand how to use threading in Python. I get
threading as a concept, but not the implementation.

In order to start threading, do you call it as a separate function,
which will then be applied to the rest of the code (functions) or do
you open threading in each function. This all can probably be answered
by 'How python threads different functions'?


Python doesn't automatically thread anything. Threading in Python is
manual. The idea is that you run your own function in a separate thread
of execution that you create. All the functions that you call from the
mentioned function (and those that they call, etc.) will then run in
those thread of execution.

You can create as many threads (probably up to some limit) as you wish
and call either the same function from them, or different functions,
depending on your application requirements.

-- Sergei.

Apr 21 '06 #2
Thanks for reply.

So would it be implemented as follows:

Func 1
Func 2
Func 3

Thread for Func 1
Thread for Func 2
Thread for Func 3

Cheers

Stevan

Apr 21 '06 #3
akrapus wrote:
Thanks for reply.

So would it be implemented as follows:

Func 1
Func 2
Func 3

Thread for Func 1
Thread for Func 2
Thread for Func 3


Could be, but the you woul most probably subclass threading.Threa d and
override the run-method.

However, often it is done like this:

def some_threaded_f unction():
while though_shalt_wo rk():
do_work()
for i in xrange(THRAD_NU M):
t = threading.Threa d(target=some_t hreaded_functio n)
t.start()
Diez
Apr 21 '06 #4
"akrapus" <ak****@gmail.c om> writes:
Thanks for reply.

So would it be implemented as follows:

Func 1
Func 2
Func 3

Thread for Func 1
Thread for Func 2
Thread for Func 3


Yes, if you wish to run every of your 3 functions in a separate thread.

-- Sergei.

Apr 21 '06 #5
akrapus wrote:
Thanks for reply.

So would it be implemented as follows:

Func 1
Func 2
Func 3

Thread for Func 1
Thread for Func 2
Thread for Func 3

Cheers

Stevan


Here's how I'm doing it, using the thread module (there's a higher
level class-based module: threading, but I'm more comfortable with the
simple one):

import thread, time

class ThreadDemo:
def __init__(self):
self.data = []
self.lock = thread.allocate _lock()
self.alive = False
def Start(self):
self.alive = True
thread.start_ne w_thread(self.P rocess, (None,))
def Stop(self):
self.alive = False
def Process(self, dummy=None):
while self.alive:
self.lock.acqui re()
self.data.sort( )
self.lock.relea se()
time.sleep(0.05 )
def Add(self, value):
self.lock.acqui re()
self.data.appen d(value)
self.lock.relea se()
from ThreadDemo import ThreadDemo
demo = ThreadDemo()
demo.Start()
demo.Add(1)
demo.Add(5)
demo.Add(2)
demo.data [1, 2, 5] demo.Add(3)
demo.data [1, 2, 3, 5] demo.Stop()
demo.Add(4)
demo.data

[1, 2, 3, 5, 4]

Use the lock whenever you are going to modify data which is shared
between more than one thread. Using time.sleep stops the thread from
hogging CPU cycles. You only need to sleep a few milliseconds. The
thread will clean itself up as soon as it's function (in this case
Process) finishes. The ugly (None,) tuple in the start_new_threa d /
dummy=None Process parameter are because the start_new_threa d function
demands a tuple of arguments, even when none are required.
see http://www.python.org/doc/current/li...le-thread.html for more
info.

Iain

Apr 21 '06 #6
Here's a recipe I used a lot:
http://aspn.activestate.com/ASPN/Coo...n/Recipe/65448

Apr 21 '06 #7
akrapus wrote:
Hi,

I am trying to understand how to use threading in Python. I get
threading as a concept, but not the implementation.

In order to start threading, do you call it as a separate function,
which will then be applied to the rest of the code (functions) or do
you open threading in each function. This all can probably be answered
by 'How python threads different functions'?

Hope if somebody can drop me a few lines. I've been trying with
different tutorials, but still do not understand.


It think many Python newcomers have similar questions (and confusion
worries about those other answers).

Maybe thats because they bought the thread/threading.Threa d/Queue stuff
and confusion from Java, C++ and that like.( And even encourages that
throw-and-pray .join()

This recipe offers BackgroundCall, which (example) you can probably
understand fuildly within a second:

http://aspn.activestate.com/ASPN/Coo.../Recipe/491280

Thus, you could forget about the technical term "thread".
As you write yoursef "..call it as a separate function..": Thats how
(new) Python programmers think naturally ?
-robert
Apr 21 '06 #8
akrapus wrote:
Hi,

I am trying to understand how to use threading in Python. I get
threading as a concept, but not the implementation.

In order to start threading, do you call it as a separate function,
which will then be applied to the rest of the code (functions) or do
you open threading in each function. This all can probably be answered
by 'How python threads different functions'?

Hope if somebody can drop me a few lines. I've been trying with
different tutorials, but still do not understand.

Cheers,

Stevan

So, I've played with python threading a fair bit, but if you don't need
to delve too far into anything special you can get away with doing
things fairly simply using the threading module

Basically (and this may be over simplifiied for this example), but you
can create a thread() object and basically pass it a function pointer.
Then you can control the thread object fairly easily with methods such
as start() and join().

So, here's an example of how I might thread a function:

#BEGIN Code
def funcToThread():
print "I'm a function"
myThread = threading.Threa d(target=functT oThread) #a function name
without parens basically yields a function pointer
myThread.start( ) #Performs necessary tasks in order to run this thread

#Here might be other stuff in your main thread of execution

myThread.join() #say you want to force synchronization at some point

#END Code

Anyhow, there are more ways to do it and it really depends on your needs
as to how far you need to take this.

Hope that helps.

-carl

--

Carl J. Van Arsdall
cv*********@mvi sta.com
Build and Release
MontaVista Software

Apr 21 '06 #9
Thanks a lot to all of you guys.
I think it'll take some time before I grasp it properly...

Apr 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

65
6702
by: Anthony_Barker | last post by:
I have been reading a book about the evolution of the Basic programming language. The author states that Basic - particularly Microsoft's version is full of compromises which crept in along the language's 30+ year evolution. What to you think python largest compromises are? The three that come to my mind are significant whitespace, dynamic typing, and that it is interpreted - not compiled. These three put python under fire and cause...
2
2968
by: Egor Bolonev | last post by:
hi all my program terminates with error i dont know why it tells 'TypeError: run() takes exactly 1 argument (10 given)' =program==================== import os, os.path, threading, sys def get_all_files(path): """return all files of folder path, scan with subfolders
77
5243
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for the moment. I'd be *very* grateful if people with any interest in multi-threading would read it (even just bits of it - it's somewhat long to go through the whole thing!) to check for accuracy, effectiveness of examples, etc. Feel free to mail...
6
555
by: CK | last post by:
I have the following code in a windows service, when I start the windows service process1 and process2 work fine , but final process (3) doesnt get called. i stop and restart the windows service and the final process(3) gets called. what am I doing wrong with the threading? by the way Directory.GetFiles(IncomingXMLPath1).Length is some global outcome from process 1. Thanks 1)
2
2240
by: Vjay77 | last post by:
In this code: Private Sub downloadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) If Not (Me.downloadUrlTextBox.Text = "") Then Me.outputGroupBox.Enabled = True Me.bytesDownloadedTextBox.Text = "" Me.totalBytesTextBox.Text = ""
11
5009
by: Paul Sijben | last post by:
I am stumped by the following problem. I have a large multi-threaded server accepting communications on one UDP port (chosen for its supposed speed). I have been profiling the code and found that the UDP communication is my biggest drain on performance! Communication where the client and the server are on the same machine still takes 300ms or sometimes much more per packet on an Athlon64 3000+ running Linux (Fedora Core 5 x64). I must...
17
6405
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. Note, the Windows task manager shows 2 CPUs on the Performance tab with hyper-threading is turned on. Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this problem. The operating system is MS Windows XP Professional.
0
1580
by: kingcrowbar.list | last post by:
Hello Everyone I have been playing a little with pyGTK and threading to come up with simple alert dialog which plays a sound in the background. The need for threading came when in the first version i made, the gui would freeze after clicking the close button until pygame finished playing the sound. In Windows it was acceptable because it could be ignored easily, but in
7
2367
by: Mike P | last post by:
I am trying to write my first program using threading..basically I am moving messages from an Outlook inbox and want to show the user where the process is up to without having to wait until it has finished. I am trying to follow this example : http://www.codeproject.com/cs/miscctrl/progressdialog.asp But although the messages still get moved, the progress window never does anything. Here is my code in full, if anybody who knows...
126
6662
by: Dann Corbit | last post by:
Rather than create a new way of doing things: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html why not just pick up ACE into the existing standard: http://www.cse.wustl.edu/~schmidt/ACE.html the same way that the STL (and subsequently BOOST) have been subsumed? Since it already runs on zillions of platforms, they have obviously worked most of the kinks out of the generalized threading and processes idea (along with many...
0
8425
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8418
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8288
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6743
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5886
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3912
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3958
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1541
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1271
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.