473,770 Members | 1,948 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question about threading

hi i have a program that listens socket connection and serial device.
in main program i am creating a socket then calling a class to listen
socket under while 1: ,
class soket(Thread):
def __init__(self):
Thread.__init__ (self)
self.host = '127.0.0.1'
self.port = 4500
self.data = ''
try:
self.s = socket.socket(s ocket.AF_INET,s ocket.SOCK_STRE AM)
self.s.bind((se lf.host,self.po rt))
self.s.listen(1 )
except:
print 'error creating a socket !?!'
def run(self):
Thread.__init__ (self)
self.conn, self.addr = self.s.accept()
self.data += self.conn.recv( 1024)
if not self.data:
pass
else:
return trim(self.data)
self.conn.close ()
in main after doing this ,
try:
s = AboutSocket.sok et()
s.setDaemon(1)
s.start()
except:
print 'Error occured while using Threaded Socket !?!'

after creating a socket i put bot soket and serial listeners in same while 1:

while 1:
skcgelen = s.run()
print '\n\nreceived data from socket : ' + skcgelen.__str_ _()
okunan = serial_readline (ser,'[ETX]')
print '\n\nreceived data : ' + okunan.__str__( )
# ser.write('[ACK]')
# database_relati on(db,okunan)

this works but when i send message to serial, the program waits for
socket to receive message, if i send a message to a socket it prints
both socket message and serial device message, how can i work them
separetly. i want to see the message from the serial if received
immediately and socket if socket receives immediately. i`ll put these
incoming message to the list dynamically.
note: serial device listener is not threaded.
thanks
Aug 17 '05 #1
1 1533
On Wed, 17 Aug 2005 12:54:49 +0300, "sinan ."
<or************ *@gmail.com> declaimed the following in comp.lang.pytho n:
def run(self):
Thread.__init__ (self)
self.conn, self.addr = self.s.accept()
self.data += self.conn.recv( 1024)
if not self.data:
pass
else:
return trim(self.data)
self.conn.close ()
Why are you creating a whole thread that just dies after the first
data is received?
in main after doing this ,
try:
s = AboutSocket.sok et()
s.setDaemon(1)
s.start()
except:
print 'Error occured while using Threaded Socket !?!'

after creating a socket i put bot soket and serial listeners in same while 1:

while 1:
skcgelen = s.run()
This is NOT how you are supposed to use threads. Threads are
supposed run asynchronously. You should have a "while True:" loop INSIDE
the run method (and you shouldn't be calling it directly, as I recall --
the start() method will call the run()). run() should not use a "return"
call.

If you are on a UNIX/Linux system, you wouldn't use the thread, and
instead use a select() call to find out if /either/ the socket or the
serial port had data. select() only works with sockets on Windows, so
that approach won't work.
print '\n\nreceived data from socket : ' + skcgelen.__str_ _()
okunan = serial_readline (ser,'[ETX]')
This is also a synchronous action, to my knowledge -- a readline
won't return until the end-of-line has been seen.
print '\n\nreceived data : ' + okunan.__str__( )
# ser.write('[ACK]')
# database_relati on(db,okunan)

this works but when i send message to serial, the program waits for
socket to receive message, if i send a message to a socket it prints
both socket message and serial device message, how can i work them
separetly. i want to see the message from the serial if received
immediately and socket if socket receives immediately. i`ll put these
incoming message to the list dynamically.
note: serial device listener is not threaded.
Neither of these is threaded as you are using them.
Pseudo-code:

mainQ = Queue.Queue()

#SerialThread:
#open serial port
while True:
data = serial_readline (ser, "[ETX]")
mainQ.put(("SER IAL", data))

#SocketThread:
#create socket and listen
while True:
conn, addr = s.accept()
data = conn.recv(1024)
mainQ.put(("SOC KET", data))
conn.close()
#Main program
create serial thread
create socket thread
while True:
(who, data) = mainQ.get()
if who == "SERIAL":
process serial data
elif who == "SOCKET":
process socket data
else:
#protocol error -- something did a mainQ.put() with bad
#arguments

Note that, if you need to reply to the socket, you do NOT want the
thread to close the connection -- and may need to pass conn as part of
the mainQ.put() data so the main thread can access the connection (and
close it).
-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Aug 17 '05 #2

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

Similar topics

3
1494
by: David Harrison | last post by:
I am working on an application on Mac OS X that calls out to python via PyImport_ImportModule(). I find that if the imported module creates and starts a python thread, the thread seems to be killed when the import of the module is complete. Is this expected? Does python have to be in control to allow threads to run? Would it be better to arrange things such that the file is processed using PyRun_SimpleFile? David S. Harrison
5
2142
by: Richard P | last post by:
I need some help on timers. My app is asp.net 1.1 website running in a shared hosting environment with a third-party service provider. I currently request and cache 20 - 40 remote RSS feeds. When a user requests the page, the app first tries to retrieve a feed from cache, if the feed has expired, it goes off and request the file from the web. If create a CacheItemRemovedCallback for each item to automatically re-request an expired...
11
4270
by: Mark Yudkin | last post by:
The documentation is unclear (at least to me) on the permissibility of accessing DB2 (8.1.5) concurrently on and from Windows 2000 / XP / 2003, with separate transactions scope, from separate threads of a multithreaded program using embedded SQL. Since the threads do not need to share transaction scopes, the sqleAttachToCtx family of APIs do not seem to be necessary. <quote> In the default implementation of threaded applications against...
13
7472
by: William Stacey | last post by:
Using the following code sample: public byte Get() { // <= Possible to switch Here?? lock(syncLock) { //Do something in Get(). } }
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)
4
1208
by: Roger | last post by:
I have a function that is currently wrapped up in a Class so I can pass a variable to it. This function is going to be threaded out and I would like the class function to be able to update a control on my form. (Treeview). Is this possible and how do I do it? Here is a simplisitc overview of what I am doing...
6
1678
by: DarkBlue | last post by:
My application makes several connections to a remote database server via tcp/ip. Usually all is fine,but occasionally the server is down or the internet does not work and then there is the 30 sec to several minutes timeout wait for the tcp to give up. Is there anything I can do without using threads,sockets,twisted etc. to have following : pseudocode :
4
321
by: DBC User | last post by:
I have a background process which reads a table to see if there are any pending requests. If there are any, then it will start a worker thread (only 10 allowed at a time) and executes a method. In this method, I iniate a PROCESS and on completion, it reduces the available worker thread and continue. I have couple of questions; 1. Since I am launching multiple threads on a same method, do I have to take care of locking so that each one...
4
1605
by: Steven | last post by:
I am taking an "advanced" VB.Net course via web at a state university toward an information science degree. This is my second VB class and I am kind of disappointed in it. This week we covered threading. The instructor is of the opinion that threading is not very useful and glossed over the subject. At least he admitted that he was glossing it over. I've noticed that many of the postings on this board have to do with threading and I...
19
1807
by: frankiespark | last post by:
Hello all, I was perusing the internet for information on threading when I came across this group. Since there seems to be a lot of good ideas and useful info I thought I'd pose a question. Threading is a new concept for me to implement. Here is my problem. I have a system that receives xml files and records their file locations in a database. I can potentially receive thousands,
0
9618
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10259
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
10101
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...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9906
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
8933
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...
0
5354
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.