473,836 Members | 1,626 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threading Problem

Hello *,
i am experimenting with threads and get puzzling results.
Consider the following example:
#--------------------
import threading, time

def threadfunction( ):
.....print "threadfunction : entered"
.....x = 10
.....while x < 40:
.........time.s leep(1) # time unit is seconds
.........print "threadfunc tion x=%d" % x
.........x += 10

print "start"
th = threading.Threa d(target = threadfunction( ))
th.start()
print "start completed"
#--------------------
(the dots are inserted becaus Google mangles the lines otherwise)

This program gives the following result :
----
start
threadfunction: entered
threadfunction x=10
threadfunction x=20
threadfunction x=30
start completed
----
My aim was that the main program should continue to run while
threadfunction runs in parallel. That's the point of threads after all,
isn't it ?

I awaited something like the following :
start
threadfunction: entered
start completed <-------------------
threadfunction x=10
threadfunction x=20
threadfunction x=30

Does anyone know what's going on here ?

Thanks for listening !

Norbert

Jul 18 '05 #1
7 1196
Norbert wrote:
Hello *,
i am experimenting with threads and get puzzling results.
Consider the following example:
#--------------------
import threading, time

def threadfunction( ):
.....print "threadfunction : entered"
.....x = 10
.....while x < 40:
.........time.s leep(1) # time unit is seconds
.........print "threadfunc tion x=%d" % x
.........x += 10

print "start"
th = threading.Threa d(target = threadfunction( ))
th.start()
print "start completed"
#--------------------
(the dots are inserted becaus Google mangles the lines otherwise)

This program gives the following result :
----
start
threadfunction: entered
threadfunction x=10
threadfunction x=20
threadfunction x=30
start completed
----
My aim was that the main program should continue to run while
threadfunction runs in parallel. That's the point of threads after all,
isn't it ?

I awaited something like the following :
start
threadfunction: entered
start completed <-------------------
threadfunction x=10
threadfunction x=20
threadfunction x=30

Does anyone know what's going on here ?


Well, I don't believe there's any guarantee that a thread will get run
preference over its starter - they're both threads, after all. Try
putting a sleep after th.start() and before the print statement and you
should see that the "worker" thread runs while the main thread sleeps.

The same would be true if each were making OS calls and so on. When
everything is more or les continuous computation, and so short it can be
over in microseconds, there's no motivation for the scheduler to stop
one thread and start another.

regards
Steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #2
[Norbert]
i am experimenting with threads and get puzzling results.
Consider the following example:
#--------------------
import threading, time

def threadfunction( ):
....print "threadfunction : entered"
....x = 10
....while x < 40:
........time.sl eep(1) # time unit is seconds
........print "threadfunc tion x=%d" % x
........x += 10

print "start"
th = threading.Threa d(target = threadfunction( ))
The problem is here ^^

You are *invoking* threadfunction, and passing its return value as the
target, rather than passing the function itself as the target. That's
why threadfunction' s output appears in the output stream before the
thread has even started.

Try this instead

#-----------------------------------------------

import threading, time

def threadfunction( ):
print "threadfunction : entered"
x = 10
while x < 40:
time.sleep(1) # time unit is seconds
print "threadfunc tion x=%d" % x
x += 10

print "start"
th = threading.Threa d(target = threadfunction)
th.start()
print "start completed"

#------------------------------------------------

Which should output the expected

start
threadfunction: entered
start completed
threadfunction x=10
threadfunction x=20
threadfunction x=30

regards,

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
Jul 18 '05 #3
Thanks a lot, Steve, for your fast reply.
But the behaviour is the same if 'threadfunction ' sleeps longer than
just 1 second. 'threadfunction ' is of course a dummy to show the
problem, imagine a longrunning background-task.

If you are right, the question remains 'How can I assure that the
starting function finishes, while the other thread still runs ?' . As
I said, this is the purpose of threading.

Thanks again
Norbert

Jul 18 '05 #4
Thanks Alan,
i hoped it would be something trivial :)

Norbert

Jul 18 '05 #5
Steve Holden wrote:
Well, I don't believe there's any guarantee that a thread will get run preference over its
starter - they're both threads, after all. Try putting a sleep after th.start() and before the
print statement and you should see that the "worker" thread runs while the main thread sleeps.


that's correct, but the "threading" module does a 0.000001-second sleep
to get around this, no matter what thread scheduler you're using.

if you're building threads on top of the lower-level "thread" api, you have
to do that yourself.

</F>

Jul 18 '05 #6
On Wed, 22 Dec 2004 12:55:46 +0000, Alan Kennedy <al****@hotmail .com> wrote:
[Norbert]
i am experimenting with threads and get puzzling results.
Consider the following example:
#--------------------
import threading, time

def threadfunction( ):
....print "threadfunction : entered"
....x = 10
....while x < 40:
........time.sl eep(1) # time unit is seconds
........print "threadfunc tion x=%d" % x
........x += 10

print "start"
th = threading.Threa d(target = threadfunction( ))


The problem is here ^^

You are *invoking* threadfunction, and passing its return value as the
target, rather than passing the function itself as the target. That's
why threadfunction' s output appears in the output stream before the
thread has even started.

Try this instead

#-----------------------------------------------

import threading, time

def threadfunction( ):
print "threadfunction : entered"
x = 10
while x < 40:
time.sleep(1) # time unit is seconds
print "threadfunc tion x=%d" % x
x += 10

print "start"
th = threading.Threa d(target = threadfunction)
th.start()
print "start completed"

#------------------------------------------------

Which should output the expected

start
threadfunction: entered
start completed
threadfunction x=10
threadfunction x=20
threadfunction x=30

regards,

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan


nice chum ;) liked the way you explained. Clear and easy to
understand.. why doesn't the keyboardInterru pt seem to work? I am
working in IDLE and it doesn't seem to stop the thread ???!!??
output of above code in IDLE shell:----

threadfunction x=75

KeyboardInterru pt

threadfunction x=80

--
cheers,
Ishwor Gurung
Jul 18 '05 #7
On Wed, 22 Dec 2004 12:55:46 +0000, Alan Kennedy <al****@hotmail .com> wrote:
[Norbert]
i am experimenting with threads and get puzzling results.
Consider the following example:
#--------------------
import threading, time

def threadfunction( ):
....print "threadfunction : entered"
....x = 10
....while x < 40:
........time.sl eep(1) # time unit is seconds
........print "threadfunc tion x=%d" % x
........x += 10

print "start"
th = threading.Threa d(target = threadfunction( ))


The problem is here ^^

You are *invoking* threadfunction, and passing its return value as the
target, rather than passing the function itself as the target. That's
why threadfunction' s output appears in the output stream before the
thread has even started.

Try this instead

#-----------------------------------------------

import threading, time

def threadfunction( ):
print "threadfunction : entered"
x = 10
while x < 40:
time.sleep(1) # time unit is seconds
print "threadfunc tion x=%d" % x
x += 10

print "start"
th = threading.Threa d(target = threadfunction)
th.start()
print "start completed"

#------------------------------------------------

Which should output the expected

start
threadfunction: entered
start completed
threadfunction x=10
threadfunction x=20
threadfunction x=30

regards,

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan


nice chum ;) liked the way you explained. Clear and easy to
understand.. why doesn't the keyboardInterru pt seem to work? I am
working in IDLE and it doesn't seem to stop the thread ???!!??
output of above code in IDLE shell:----

threadfunction x=75

KeyboardInterru pt

threadfunction x=80

--
cheers,
Ishwor Gurung
Jul 18 '05 #8

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

Similar topics

65
6774
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
2997
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
5396
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...
77
2884
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...
11
5049
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...
0
9825
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
9673
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
10560
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
10602
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
9388
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
6984
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4463
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3116
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.