473,657 Members | 2,504 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

print in multithreaded environement ???

What will be the result if I have several threads that print to
different buffers ?

I have several threads, each one execute different python code.
Just before the "exec" of this small python code, I redirect the
output to a "buffer".
Each thread has his own buffer.
What will be the result when they print at the same time ?

Does sys.stdout is a seperate instance for each thread ?
Does sys.stdout is shared between all of them ?

Does any one has experience with that ?

Thanks.
Jul 18 '05 #1
4 6387
> Does sys.stdout is a seperate instance for each thread ?
Does sys.stdout is shared between all of them ?
sys.stdout, sys.stdin and sys.stderr are all shared.

Does any one has experience with that ?


Yes. As soon as a thread uses up its timeslice, it is paused. Sending
a lot of information to sys.stdout, or doing any non-trivial computation
is a good way of using up a timeslice...as is sleeping for an
arbitrarily small amount of time, even 0.

Run the following code to see how it behaves.

import time
from threading import Thread
def funct(i):
for j in xrange(50):
print i,
time.sleep(0)

for i in xrange(50): Thread(target=f unct, args=(i,)).star t()
- Josiah
Jul 18 '05 #2
Thanks Josiah for the answer.

but in my case each thread will have his own buffer and stdout will be
redirect to it.

Following your example, I think that what I'm talking about should be like
this :
import time
from threading import Thread
import sys
def funct(i):
fid=open('/tmp/tt%s.tt' % i,'w')
sys.stdout=fid
for j in xrange(50):
print i,j,
time.sleep(0)
fid.close()
for i in xrange(50): Thread(target=f unct, args=(i,)).star t()

If I run it, I've the result I expected: counter from 0 to 49 in each file.
Thus sys.stdout is not a shared object between each thread. It's his
redirection to the console which is common.
Thus, problems occurs when we link it to a shared output (like a console or
single output file).

Am I correct ?


Josiah Carlson wrote:
Does sys.stdout is a seperate instance for each thread ?
Does sys.stdout is shared between all of them ?


sys.stdout, sys.stdin and sys.stderr are all shared.

Does any one has experience with that ?


Yes. As soon as a thread uses up its timeslice, it is paused. Sending
a lot of information to sys.stdout, or doing any non-trivial computation
is a good way of using up a timeslice...as is sleeping for an
arbitrarily small amount of time, even 0.

Run the following code to see how it behaves.

import time
from threading import Thread
def funct(i):
for j in xrange(50):
print i,
time.sleep(0)

for i in xrange(50): Thread(target=f unct, args=(i,)).star t()
- Josiah


Jul 18 '05 #3
On 2004-02-26 00:37:23 -0500, vi***********@y ahoo.com said:
Thanks Josiah for the answer.
but in my case each thread will have his own buffer and stdout will be
redirect to it.

Following your example, I think that what I'm talking about should be like
this :
import time
from threading import Thread
import sys
def funct(i):
fid=open('/tmp/tt%s.tt' % i,'w')
sys.stdout=fid
for j in xrange(50):
print i,j,
time.sleep(0)
fid.close()
for i in xrange(50): Thread(target=f unct, args=(i,)).star t()

If I run it, I've the result I expected: counter from 0 to 49 in each file.
Thus sys.stdout is not a shared object between each thread. It's his
redirection to the console which is common. Thus, problems occurs when
we link it to a shared output (like a console or
single output file).

Am I correct ?


What you actually want to try and do is:

print >>fid, i, j,

Using a global output for multiple threads at the same time is an
absolutely awful idea..

dont_try_this_a t_home = """
it is possible to make sys.stdout a special kind of object that writes
to different streams depending on the thread id, or at least I would
assume so because I have done it for stackless tasklets. However, the
*only* reason I did it that way because what I was writing was an
multi-interpreter GUI environment, so the print statements and
sys.stdout were something I did not have any control over.

In either case, I learned a lesson trying to do this:

Python (short of PyPy) is not capable of doing in-process
"sub-interpreters" for arbitrary code in any reliable way.

If I were to hack at it again, I would rip that out and emulate IDLE.
It spawns a new process for each interpreter and communicates with it
over some kind of file descriptor (socket, pipe, etc.). This is more
scalable anyway, because Python has the dreaded GIL.
"""

My general rule is to avoid threads whenever possible, because in many
cases they aren't going to be faster anyway (unless their primary
function is to call a C function that releases the GIL, like maybe
communicating with a blocking database library) and that it is hard to
debug threaded programs that aren't working quite right. If you don't
like writing asynchronous code explicitly, look into Stackless Python ;)

-bob

Jul 18 '05 #4
In article <5c************ **************@ posting.google. com>,
vincent delft <vi***********@ yahoo.com> wrote:

What will be the result if I have several threads that print to
different buffers ?
What do you mean by "buffer"? Different file handles?
I have several threads, each one execute different python code.
Just before the "exec" of this small python code, I redirect the
output to a "buffer".
Each thread has his own buffer.
What will be the result when they print at the same time ?


If the buffer is a simple string that you're printing, the order in
which buffers are output is non-determinate (absent explicit ordering
through the use of Queue.Queue or equivalent), but the entire string
will be output as a single chunk.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"Do not taunt happy fun for loops. Do not change lists you are looping over."
--Remco Gerlich, comp.lang.pytho n
Jul 18 '05 #5

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

Similar topics

5
1886
by: vegetax | last post by:
How can i use cgi'like print statement in a multitreaded web framework? each thread has its own Servlet instance with request/response objects, sys.stdout = self.response(which is a file like object) wont work because all threads will set the same file object and it will be a concurrence mess. I am out of ideas here,so any hacks welcome =)
3
5314
by: Anthony | last post by:
Hi, How does (Can?) the stream mechanism work in multithreaded programs? I want to implement cout in my multithreaded program.
2
6634
by: pradyumna | last post by:
In Project settins - C/C++ - Code Generation, what is the difference between the option "Multithreaded" and "Multithreaded DLL". I understand that on selecting multithreaded option, single and multithreaded applications can both use that dll, but what about multithreaded DLL option. Thanks
6
2783
by: Dan Kelley | last post by:
We have a multithreaded app that responds to events, and writes these events to a text file. This text file is used by an external system for further processing. We want to be able to write multiple entries to the file, and then rename it and copy it to a new location when the file reaches a certian size, or a certain time span elapses (which ever comes first). I have created a static/shared timer member variable in class that writes...
1
1785
by: ravinder | last post by:
I wanted to develop a multithreaded program using OO concepts on windows platform. Problem: I have to simulate two layers(similar to TCP/IP stack layers), and the layer functionality is of finite state machine type i.e after receiving any event(either after receiving message or any timer expiry), state change happens internal to layer. And there will be message transfer between two layers. My idea is to put layer specific data in the class and...
3
2592
by: groups | last post by:
Hi all, I've recently ported a rather large C application to run multithreaded. A few functions have seriously deteriorated in performance, in particular when accessing a rather large global array, that contains information that is shared among threads. Any idea, why the lines accessing this global array now take about 50x longer in the multithreaded application?
3
1654
by: | last post by:
Is it possible to have just a multithreaded sub procedure? What I need is a timer time_elapsed event (2 sec interval) send params to a sub that is multithreaded. I have a COM component used to send messages,faxes, etc.. The COM com component is licensed for 6 ports. I have an app that need to send messages/faxes very frequently (seconds) and to many, many people. What I want to do is have a sub that has 6 threads to send thse messages...
3
4597
by: Jake K | last post by:
I have a multithreaded application that I now want to convert into a Windows Service. Does application.run work in a windows service? Are there things to take into consideration when creating a multithreaded windows service as opposed to a multithreaded windows forms application? E.G. namespace whatever {
0
8421
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
8844
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
8742
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
8518
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
8621
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
7354
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
5643
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
2743
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
1734
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.