473,387 Members | 1,578 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Creating multiple threads

I have a scenario where I need to do multiple things and the flow is not synchronous.

I need one thread to be listening to a socket using the recv socket api. Other thread to be sending some messages to the server and another thread performing some local action.

Which would be better way of implementing it ...

Create three threads using
thread.start_new_thread(func1)
thread.start_new_thread(func2)
thread.start_new_thread(func3)

And then have a main thread which waits, until all the threads are done executing ?

or using threading.thread module.

Any tips would be greatly appreciated ?

Also is there some kind of signal that can be raised in threads that would stop the execution of all the threads, if it hits a certain condition

Thanks,
-I
Sep 5 '07 #1
5 6132
bartonc
6,596 Expert 4TB
I prefer using thread objects from the threading module (threading.thread). They work quite well and have thread-safe means of signaling, as in:
Event( )
A factory function that returns a new event object. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.
For message passing, I use Queue objects for the Queue module (Queue.Queue).
The Queue module implements a multi-producer, multi-consumer FIFO queue. It is especially useful in threads programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python.
[Note: chapter references are for version 4.4.]
Sep 6 '07 #2
I prefer using thread objects from the threading module (threading.thread). They work quite well and have thread-safe means of signaling, as in:...
All the examples I have seen for threading module has the same function doing the same operation with multiple threads. But in my case, I need to call three different functions and I am not sure if I can use the threading module

Am I missing something really basic here ?
Sep 7 '07 #3
bartonc
6,596 Expert 4TB
All the examples I have seen for threading module has the same function doing the same operation with multiple threads. But in my case, I need to call three different functions and I am not sure if I can use the threading module

Am I missing something really basic here ?
The "target" argument of the thread creation method can be any function that you wish. In that function you would loop until signaled by one means or another by the main thread. In this simple example, there is no loop at all:
Expand|Select|Wrap|Line Numbers
  1. >>> def FuncToRunAsThread():
  2. ...     print "I ran"
  3. ...     
  4. >>> import threading
  5. >>> t = threading.Thread(target=FuncToRunAsThread)
  6. >>> t.start()
  7. I ran
  8. >>> 
I'll work up a slightly more complex example for you shortly.
Sep 7 '07 #4
bartonc
6,596 Expert 4TB
The "target" argument of the thread creation method can be any function that you wish. In that function you would loop until signaled by one means or another by the main thread. In this simple example, there is no loop at all:
Expand|Select|Wrap|Line Numbers
  1. >>> def FuncToRunAsThread():
  2. ...     print "I ran"
  3. ...     
  4. >>> import threading
  5. >>> t = threading.Thread(target=FuncToRunAsThread)
  6. >>> t.start()
  7. I ran
  8. >>> 
I'll work up a slightly more complex example for you shortly.
Expand|Select|Wrap|Line Numbers
  1. import time
  2. import threading
  3.  
  4. def FuncToRunAsThread(event):
  5.     print "started at %f" %time.time()
  6.     while not event.isSet():
  7.         pass  #do some work until the mainthread sets the event
  8.     print "stopped at %f" %time.time()
  9.  
  10. if __name__ == "__main__":
  11.     thrdHandshake = threading.Event()
  12.     workerThread = threading.Thread(target=FuncToRunAsThread, args=(thrdHandshake,))
  13.     workerThread.start()
  14.     print workerThread.isAlive()
  15.     time.sleep(5)
  16.     thrdHandshake.set()  # Set the handshake flag that will terminate the thread
  17.     workerThread.join()  # wait here until the thread is actually terminated
  18.     print workerThread.isAlive()  # without the previous line, isAlive() will usually? be true
  19.     print "main thread terminated at %f" %time.time()
started at 1189154645.265000
True
stopped at 1189154650.359000
False
main thread terminated at 1189154650.359000
Sep 7 '07 #5
Thanks for the eg. Barton.
Sep 11 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Tumurbaatar S. | last post by:
ASP.NET QuickStart Tutorial says that: .... ASP.NET maintains a pool of HttpApplication instances over the course of a Web application's lifetime. ASP.NET automatically assigns one of these...
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
2
by: Brett | last post by:
What are the advantages/disadvantages of using one process with multiple threads or doing the same task with multiple processes, each having one thread? I see using multiple threads under one...
5
by: Bob Bins | last post by:
Is there a way to create a shared lock using the Monitor class or any other synchronization class in .NET? So I have one resource that may have multiple threads using it at once but a second...
12
by: David Beoulve | last post by:
In my windows C# app, I create a thread to separate the main code block from the GUI, which recursively sorts through all the directories starting from a given point, and every time it finds a...
1
by: StuartJ | last post by:
Hi, I'm trying to create a generic threading application where you can pass in any object and a number of threads, most of it is working but I'm having trouble creating multiple instances of the...
35
by: keerthyragavendran | last post by:
hi i'm downloading a single file using multiple threads... how can i specify a particular range of bytes alone from a single large file... for example say if i need only bytes ranging from...
5
by: dk60 | last post by:
Here is a problem I encountered concerning threads: Here is the code in Form1 button click handler: AddForm addForm = new AddForm(booksDataSet.Titles); Thread addTitleThread=new Thread(new...
9
by: =?Utf-8?B?YmJn?= | last post by:
Hi all, I read somewhere "using kernel stuff in thread is not good.." if ManualResetEvent object is created in thread but not actually used, will it affect performance? Bob
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...

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.