- import threading
-
import time
-
-
class ThreadOne ( threading.Thread ):
-
def run ( self ):
-
print 'Thread', self.getName(), 'started.'
-
time.sleep ( 5 )
-
print 'Thread', self.getName(), 'ended.'
-
class ThreadTwo ( threading.Thread ):
-
def run ( self ):
-
print 'Thread', self.getName(), 'started.'
-
time.sleep ( 5 )
-
print 'Thread', self.getName(), 'ended.'
-
thingOne = ThreadOne()
-
thingOne.start()
-
thingTwo = ThreadTwo()
-
thingTwo.start()
This is the example I keep finding on threading, The problem is, I don't know how many threads I need. Basically, I was wondering if there was a command to start a new thread that runs a command already made, maybe like:
startNewThread(MyFunction(Arg1, Arg2, Arg3))
Is there such a function, Or Ideas on how I can make one? Thanks again.
16 4380 - import threading
-
import time
-
-
class ThreadOne ( threading.Thread ):
-
def run ( self ):
-
print 'Thread', self.getName(), 'started.'
-
time.sleep ( 5 )
-
print 'Thread', self.getName(), 'ended.'
-
class ThreadTwo ( threading.Thread ):
-
def run ( self ):
-
print 'Thread', self.getName(), 'started.'
-
time.sleep ( 5 )
-
print 'Thread', self.getName(), 'ended.'
-
thingOne = ThreadOne()
-
thingOne.start()
-
thingTwo = ThreadTwo()
-
thingTwo.start()
This is the example I keep finding on threading, The problem is, I don't know how many threads I need. Basically, I was wondering if there was a command to start a new thread that runs a command already made, maybe like:
startNewThread(MyFunction(Arg1, Arg2, Arg3))
Is there such a function, Or Ideas on how I can make one? Thanks again.
There is no real need to subclass threading.Thread.
"""
class Thread( group=None, target=None, name=None, args=(), kwargs={})
This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form ``Thread-N'' where N is a small decimal number.
args is the argument tuple for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.
""" -
def myFunc(arg1, arg2):
-
print 'Thread', self.getName(), 'started.'
-
print arg1, arg2
-
time.sleep ( 5 )
-
print 'Thread', self.getName(), 'ended.'
-
-
t1 = threading.Thread(group=None, target=myFunc, name=None, 1, 2)
-
t2 = threading.Thread(group=None, target=myFunc, name=None, 'a', 'b')
-
t1.start()
-
t2.start()
is what you're looking for.
Thanks once again. Don't know what I would do without you folks.
Thanks once again. Don't know what I would do without you folks.
You are welcome. That's what this site is all about!
Hmm, I'm having a little trouble with this.
My function I need executed is: quote.sendquote(connection, event)
so, the command should look like:
threading.Thread(group=None, target=quote.sendquote, name=None, connection, event)
correct?
Hmm, I'm having a little trouble with this.
My function I need executed is: quote.sendquote(connection, event)
so, the command should look like:
threading.Thread(group=None, target=quote.sendquote, name=None, connection, event)
correct?
I've never tried to use a bound method as a thread target, but it looks OK.
Does it work?
no, It doesn't. I tried a few more variations But still nothing.
no, It doesn't. I tried a few more variations But still nothing.
Paste some error messages so that we can see what you are getting.
If quote is a class, perhaps you need an instance. If it is a module try - from quote import sendquote
-
threading.Thread(group=None, target=sendquote, name=None, connection, event)
-
Posting code is very helpful in these situations.
- from quote import sendquote
-
threading.Thread(group=None, target=sendquote, name=None, connection, event)
-
this code produces the same error as what I was doing before.
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import quotebot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25\lib\quotebot.py", line 5, in <module>
import quote, ontext
File "C:\Python25\lib\ontext.py", line 48
threading.Thread(group=None, target=sendquote, name=None, connection, event)
SyntaxError: non-keyword arg after keyword arg
>>>
As for the code, Its quite a long script, but using quote.sendquote(connection, event) does work.
- from quote import sendquote
-
threading.Thread(group=None, target=sendquote, name=None, connection, event)
-
this code produces the same error as what I was doing before.
As for the code, Its quite a long script, but using quote.sendquote(connection, event) does work.
That helps a lot! Try - from quote import sendquote
-
threading.Thread(None, sendquote, None, connection, event)
nope, that doesn't produce any error messages or anything, the interpreter still is running and the bot is still working, minus the quote function.
nope, that doesn't produce any error messages or anything, the interpreter still is running and the bot is still working, minus the quote function.
Is that quote module something that you wrote? If so can you post it? Or can I download it someplace?
actually the last code you gave me works, I had copied it wrong >.>
Thanks
actually the last code you gave me works, I had copied it wrong >.>
Thanks
Oh, good. You really had me worried, there. Thanks for the update.
There is no real need to subclass threading.Thread.
"""
class Thread( group=None, target=None, name=None, args=(), kwargs={})
This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form ``Thread-N'' where N is a small decimal number.
args is the argument tuple for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.
""" -
def myFunc(arg1, arg2):
-
print 'Thread', self.getName(), 'started.'
-
print arg1, arg2
-
time.sleep ( 5 )
-
print 'Thread', self.getName(), 'ended.'
-
-
t1 = threading.Thread(group=None, target=myFunc, name=None, 1, 2)
-
t2 = threading.Thread(group=None, target=myFunc, name=None, 'a', 'b')
-
t1.start()
-
t2.start()
is what you're looking for.
Hi
I tried the above code and got an error about "global name 'self' is not defined". Also, I found that if I create a run method, the target is ignored.
Any ideas?
A
Hi
I tried the above code and got an error about "global name 'self' is not defined". Also, I found that if I create a run method, the target is ignored.
Any ideas?
A
After much development, here is a class that contains a thread: -
class USB_Device:
-
"""This device model provide direct and background reads of the file handle.
-
The read() function chooses which to use based on the state of the Event().
-
All exceptions are passed up to the level above: direct reads use raise and
-
background reads put the error into the Queue().
-
"""
-
def __del__(self):
-
self.Close()
-
-
def __init__(self, devHandle, packetSize):
-
"""USB_Device(C_TYPE_HANDLE, pyInt)"""
-
self.devHandle = devHandle
-
self.packetSize = packetSize
-
-
self.recQueue = Queue() # Queue for receiving packets
-
self.runEvent = threading.Event()
-
self.listener = None
-
self.running = False
-
-
def StartBgRead(self):
-
"""Create a background thread, set the runEvent and start the thread,
-
if one is not already running. Keep a reference for Stop() to use.
-
"""
-
if not self.running:
-
self.listener = threading.Thread(target=self.BgRead, args=(self.devHandle,
-
self.recQueue, self.runEvent))
-
self.runEvent.set()
-
self.listener.start()
-
self.running = True
-
-
def StopBgRead(self):
-
"""if bg is running, clear the runEvent, join() the bg task
-
if it is alive and wait 1.5 seconds for it to die. Return
-
success (as the inverse of the state of the bg task)
-
"""
-
state = True
-
if self.running:
-
self.runEvent.clear()
-
self.running = False
-
if self.listener is not None:
-
if self.listener.isAlive():
-
self.listener.join(1.5)
-
state = not self.listener.isAlive()
-
return state
-
-
def BgRead(self, devHandle, outQueue, runEvent):
-
"""Don't use the self variable. Threads don't have true (thread-safe)
-
access to shared py objects. I'd move it to the module scope, but
-
it's just so much easier to see here.
-
"""
-
try:
-
# run until an error occures or the main thread signals here
-
while runEvent.isSet():
-
thePacket = _read(devHandle)
-
outQueue.put(thePacket)
-
# just here for debugging, really #
-
outQueue.put("Background terminated normally.")
-
except WindowsError, error:
-
# Put the error on the queue.
-
outQueue.put(error)
-
self.runEvent.clear() # infrom main thread of exit
-
-
def read(self):
-
"""Background reads return None if there is nothing in the queue.
-
Errors in the background thread are put into the queue and the
-
thread exits.
-
Direct reads block until data has been read or an error occures.
-
Errors propogate up the call chain.
-
elif and else used for readablity, not program flow.
-
"""
-
if self.runEvent.isSet():
-
try:
-
return self.recQueue.get(timeout=.1)
-
except Empty:
-
return
-
elif self.running:
-
# the background thread terminated
-
try:
-
bgData = self.recQueue.get(timeout=.1)
-
except Empty: # should always get an Exception instance from the queue
-
print 'empty q data:', bgData
-
bgData = None
-
# Flush the queue:
-
while not self.recQueue.empty():
-
try:
-
self.recQueue.get(timeout=.1)
-
except Empty:
-
break
-
self.running = False
-
self.listener = None
-
return bgData
-
else:
-
try:
-
return _read(self.devHandle)
-
except WindowsError:
-
raise
-
-
def write(self, aPacket):
-
"""Bulk pipe write"""
-
nBytesToWrite = DWORD(sizeof(aPacket))
-
nBytesReturned = DWORD(0)
-
-
success = WriteFile(self.devHandle,
-
byref(aPacket),
-
nBytesToWrite,
-
byref(nBytesReturned),
-
None)
-
if not success:
-
raise WinError()
-
-
##// If the packet size was an exact multiple of the USB packet
-
##// size, we must make a final write call with no data
-
if (nBytesToWrite.value % self.packetSize) == 0:
-
success = WriteFile(self.devHandle,
-
DWORD(0), DWORD(0),
-
byref(nBytesReturned),
-
None)
-
if not success:
-
raise WinError()
-
-
-
def ExpectPacketTypeAndID(self, pktType, pktId):
-
""""""
-
thePacket = self.read()
-
if (thePacket.mPacketType != pktType) or (thePacket.mPacketId != pktId):
-
msg = "Expected packet type %d, ID %d. Got type %d, ID %d"\
-
%(pktType, pktId, thePacket.mPacketType, thePacket.mPacketId)
-
if thePacket.mDataSize:
-
msg += " with data: %s" %str(thePacket.mData[:])
-
raise PyGarUSBError(msg)
-
return thePacket
-
-
def Close(self):
-
self.StopBgRead()
-
-
-
-
-
def _read(devHandle):
-
"""Read async data until the driver returns less than the
-
max async data size, which signifies the end of a packet."""
-
pass
Bumping thread because I can't figure out a lasting way to link to search results.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: RobertMaas |
last post by:
After many years of using LISP, I'm taking a class in Java and finding
the two roughly comparable in some ways and very different in other
ways. Each has a decent size library of useful utilities...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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.
...
|
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...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
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...
|
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
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
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...
|
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...
|
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...
|
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...
| |