473,797 Members | 3,187 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

returning a value from a thread

module1 calls a function in module2

module2 starts a thread that calls a function in module3
and then returns to module1

thread finishes and I need the return value from the thread
to use in module1 where program flow is continuing.

err, I hope I explained that well enough?

In other words need value from module3 passed
back to module1 (global variable)

I thought there was some sort of memory type container
I could use...

ie. store value in memory from module3 and be able to
read it from module1.

The closest I can think of is to pass a queue reference
and stor values from module3 in the queue and then read them
back while in module1.

Maybe I'm missing something?

Jul 18 '05 #1
20 2967
On Wed, 14 Jul 2004, Ken Godee wrote:
I thought there was some sort of memory type container
I could use...

ie. store value in memory from module3 and be able to
read it from module1.

The closest I can think of is to pass a queue reference
and stor values from module3 in the queue and then read them
back while in module1.


Actually, any kind of container object would do: you could pass a list,
dictionary, or class to the thread, and the thread could store its results
in it.

A hackish method would be to pass the dictionary returned by locals() in
module1 to the thread. This way the thread could set a value in module1
directly.

Just don't forget to .join() on the thread in module1 before accessing the
container object! (Assuming you're using threading) I just wish Python's
..join() could return values, like pthread_join can.

Jul 18 '05 #2
Christopher T King <sq******@WPI.E DU> writes:
Just don't forget to .join() on the thread in module1 before accessing the
container object! (Assuming you're using threading) I just wish Python's
.join() could return values, like pthread_join can.


Although if you can join on the thread, then you have to have a
reference to the thread object, at which point you can do anything you
want in terms of permitting state to be interrogated on that object
(direct attribute access, getters, etc...), which is even better than
having join return an object.

-- David
Jul 18 '05 #3
Christopher T King wrote:
On Wed, 14 Jul 2004, Ken Godee wrote:
I thought there was some sort of memory type container
I could use...

ie. store value in memory from module3 and be able to
read it from module1.

The closest I can think of is to pass a queue reference
and stor values from module3 in the queue and then read them
back while in module1.


Actually, any kind of container object would do: you could pass a list,
dictionary, or class to the thread, and the thread could store its results
in it.

A hackish method would be to pass the dictionary returned by locals() in
module1 to the thread. This way the thread could set a value in module1
directly.

Just don't forget to .join() on the thread in module1 before accessing the
container object! (Assuming you're using threading) I just wish Python's
.join() could return values, like pthread_join can.


This may work if the worker thread will perform a relatively short task
and then die *before* you access the result. But lists and dictionaries
are not thread-safe -- if they are potentially accessed by multiple
threads concurrently, then the behavior will be unpredictable. (Think
of a case where thread B starts to update a dictionary, inserts a key
but is interrupted before it can attach a value to that key, and then
while thread B is interrupted thread A looks at the dictionary and finds
the key it's looking for, but with no valid reference as its value...
[Disclaimer: I don't know the inner workings of dictionaries well enough
to know if this exact situation is possible, but I do know that dicts
are not threadsafe, so something *similar* is possible...])

Unless you're certain that your worker thread can die before you get the
results, and you're able to have your main thread potentially sit around
doing nothing until that happens (which is what join() does), you need
to use a threadsafe method of passing data back and forth. The simplest
such method is indeed to use a queue. You *can* use some other
container, and protect access to that container through the use of
locks.... but that's exactly what a queue does, so why reinvent the wheel?

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #4
On Wed, 14 Jul 2004, Jeff Shannon wrote:
Christopher T King wrote:
Just don't forget to .join() on the thread in module1 before accessing the
container object! (Assuming you're using threading) I just wish Python's
.join() could return values, like pthread_join can.


This may work if the worker thread will perform a relatively short task
and then die *before* you access the result. But lists and dictionaries
are not thread-safe -- if they are potentially accessed by multiple
threads concurrently, then the behavior will be unpredictable.


That's where the .join() comes in handy (it blocks until the thread dies)
;)

Jul 18 '05 #5
Ken Godee wrote:

[detailed version of the question in the subject line]

This question is asked often enough that it maybe should
become a FAQ, but in any case it was asked a few weeks
ago and I posted sample code with the idiomatic approach,
as I recall. A Google Groups search with your keywords
and my name should find it pretty quick.

-Peter
Jul 18 '05 #6
Peter Hansen wrote:
Ken Godee wrote:

[detailed version of the question in the subject line]

This question is asked often enough that it maybe should
become a FAQ, but in any case it was asked a few weeks
ago and I posted sample code with the idiomatic approach,
as I recall. A Google Groups search with your keywords
and my name should find it pretty quick.


Oops, doesn't look like I'm remembering the right thread,
since I didn't post in it. Anand Pillai, however, did
post sample code:

http://groups.google.ca/groups?hl=en...9006da0&rnum=1

-Peter
Jul 18 '05 #7
Peter Hansen wrote:
Peter Hansen wrote:
Ken Godee wrote:

[detailed version of the question in the subject line]

This question is asked often enough that it maybe should
become a FAQ, but in any case it was asked a few weeks
ago and I posted sample code with the idiomatic approach,
as I recall. A Google Groups search with your keywords
and my name should find it pretty quick.


Oops, doesn't look like I'm remembering the right thread,
since I didn't post in it. Anand Pillai, however, did
post sample code:


Actually, my memory is better than my search skills today:

http://groups.google.ca/groups?selm=...40powergate.ca
Jul 18 '05 #8
Christopher T King wrote:
On Wed, 14 Jul 2004, Jeff Shannon wrote:
Christopher T King wrote:
Just don't forget to .join() on the thread in module1 before accessing the
container object! (Assuming you're using threading) I just wish Python's
.join() could return values, like pthread_join can.

This may work if the worker thread will perform a relatively short task
and then die *before* you access the result. But lists and dictionaries
are not thread-safe -- if they are potentially accessed by multiple
threads concurrently, then the behavior will be unpredictable.


That's where the .join() comes in handy (it blocks until the thread dies)
;)


True, but quite frankly, I don't see much value in starting a new thread
if you're only going to be sitting around waiting for that thread to
finish. At that point, where's the gain over simply calling a
function? This may be a matter of style, but I see two major uses for
worker threads. In one case, you're doing a little bit of work here, a
little bit of work there, a little bit here again... back and forth.
The other is the case where you have a long-running task, but want your
user interface to remain responsive while that task running. (For
instance, most GUI frameworks will have problems if their event queues
aren't serviced regularly, and a lengthy calculation can prevent that
unless you put it in another thread.) This would also include the case
of a service/daemon which must remain responsive to new requests, so it
fires up a separate thread to handle each incoming request. In the
first case, you need to synchronize execution between the threads at
multiple points; in the second, the threads each go about their own
thing until the worker is finished, at which point it must notify the
main thread. In neither case is it practical to join() the worker
thread, because the whole point is that the main thread can't just sit
and do nothing.

If you *are* going to join(), then the advantages of concurrent
execution get thrown away while sitting at that join(). I see no
practical advantage of this:

workerthread = threading.Threa d(target=somefu nc)
workerthread.ru n()
somestuff()
someotherstuff( )
workerthread.jo in()

vs this:

somestuff()
someotherstuff( )
somefunc()

The only way you could possibly get a speed advantage from using a
thread is on a multiprocessor machine, and I don't believe that Python
currently makes use of multiple processors anyhow (though I think that
it's possible for C extension modules to do so). The flow-control
advantage of using a thread, that your program flow doesn't have to wait
for the task to finish, is lost when you are waiting to join(). All
you're left with is the added complexity. Now, if the worker thread
needs to finish some subtask before, say, someotherstuff( ) is called,
then you've got a potential for flow-control advantage... but you also
need synchronization that's a lot more advanced than just waiting for
the thread to die. If you don't need thread-safe communication between
the threads, then you don't need threads, at least IMO.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #9
>>ie. store value in memory from module3 and be able to
read it from module1.

The closest I can think of is to pass a queue reference
and stor values from module3 in the queue and then read them
back while in module1.

Actually, any kind of container object would do: you could pass a list,
dictionary, or class to the thread, and the thread could store its results
in it.


This was my orginal problem, being the middle man (module2) that spins
the thread(calling function in module3) has returned to module1 before
the thread result was available. So I couldn't figure a way to get the
result from module3 back to a global var in module1, since middle man
was gone.

A hackish method would be to pass the dictionary returned by locals() in
module1 to the thread. This way the thread could set a value in module1
directly.
Hhmmm, interesting, didn't know you could do that. Might have to try it.
Just don't forget to .join() on the thread in module1 before accessing the
container object! (Assuming you're using threading) I just wish Python's
.join() could return values, like pthread_join can.

Using thread here.
But I really have nothing against using queue, I've used queues before
but more for a kind of stream of data and was thinking I was missing
something because I only want to pass back a single value, so Queue(1)
would probally be alright.

Thanks for all the responses.

Ken

Jul 18 '05 #10

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

Similar topics

9
11917
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is up to which size m would you expect vector<double> returns_by_value() {
11
2069
by: kelvSYC | last post by:
What is the best way to create functions that, based on some input, return either structures or a null value if the structure cannot be made? The problem is that the structure has be created inside the function, and I've heard that returning a pointer to a locally created structure is unsafe. -- I am only a mirage.
19
1987
by: JKop | last post by:
When I compile and run the following on my system: #include <iostream> static int hello = 78; int ReturnValue(void) {
13
4521
by: Matthias Kaeppler | last post by:
Hi, I was wondering why library implementors often make getter functions return strings by value (copies). For example, in boost::filesystem the leaf() function returns an std::string by value. So does Gnome::Vfs::FileInfo::get_name(). Isn't that unnecessary overhead? I could as well return by reference to const-string and avoid
1
5228
by: Jim P. | last post by:
I'm having trouble returning an object from an AsyncCallback called inside a threaded infinite loop. I'm working on a Peer2Peer app that uses an AsyncCallback to rerieve the data from the remote peer. I have no problem connecting the peers and streaming Network Streams. When the incoming data is finished recieving, I act upon it. This works great as long as all of the code is inside my form. I want to build the networking code into a...
1
1306
by: Pesso | last post by:
I have a worker thread, which returns a value (a System.Xml.XmlDocument object) to the main WinForm thread. I tried the below, but I'm not sure if it's done correctly. public class Form1: System.Windows.Forms.Form { // ... System.Xml.XmlDocument _xmldoc; // ... void Func1()
5
10378
by: LS | last post by:
Can a WebMethod return an Interface type? Can we pass an interface parameter ? Example : public interface IEntity { long Id { get; set; } string Name { get; set; } }
9
5214
by: Thomas Mlynarczyk | last post by:
Hi, It seems to be a generally adopted convention to have a function return FALSE in case of an error. But if a function is supposed to return a boolean anyway, one cannot distinguish anymore between the "normal" FALSE and the "error" FALSE. So why not using NULL instead to indicate an error? Are there drawbacks I am not aware of? Greetings, Thomas
4
9031
by: otengo | last post by:
Hi all, I tried using GetCurrentThread to get the Handle of the current thread but it keeps returning 0xfffffffe for all the threads that I access it in. This is not the correct handle. Am I missing any prerequisite calls or something else? Regards, ...ab
0
9685
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
10469
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
10246
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
10209
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
10023
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
9066
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
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3750
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2934
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.