473,239 Members | 1,779 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,239 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 6129
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
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...

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.