468,511 Members | 1,514 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,511 developers. It's quick & easy.

Global vs local streams in a multithreaded app

I'm maintaining a C++ application written by a developer who has now
left. The app is a multithreaded client/server app for financial data.
My compiler is MS visual C++ 6.0.

I'm a C++ neophyte. I took some C (not C++) courses in college, this is
the only production C++ code I've worked with.

I'm trying to add some logging, and having problems.

My logging scheme is to have a global ofstream, which I initialize in a
function by creating a local ofstream, preparing it, and assigning it
to the global name.

The problem is that I can << to the local name without trouble, but I
get an access violation when I try to << to the global stream (after
assigning global = local).

I think the problem may be due to the multithreaded nature of the
application, but am unsure. At the moment, I'm only <<ing to the log
in one function, in the main (server) thread of the app. There are no
multiple concurrent accesses to the global log.

This code demonstrates the nub of the problem:

-----Globals.h-------

#include <fstream>

class GLOBALS
{
public:
ofstream GlobalLog;
}

------SomeOtherFile.cpp-------
#include "Globals.h"

extern GLOBALS * g; // This is populated properly, I just don't show
that here.

void foo()
{
if(!g->GlobalLog.is_open())
{
ofstream localNameForTheLog("c:\\thelogIwant.log" , ios::out |
ios::ate | ios::app);

if(!localNameForTheLog.is_open())
{
cout << "Couldn't open log.";
return;
}

localNameForTheLog << "Some stuff I'm able to log successfully";

g->GlobalLog = localNameForTheLog;

}

// If we got here, either GlobalLog was already open,
// or we just successfully opened it.
g->GlobalLog << "This causes an access violation for some reason, even
though I just logged the line above.";

}

Jul 23 '05 #1
1 2090
da*********@gmail.com wrote:

g->GlobalLog = localNameForTheLog;


iostreams aren't assignable. This line only "works" because there is a
secret assignment operator that's used during initialization. It doesn't
do a proper assignment, though.

But there's no need to go through all this indirection. Just open the
global stream using ofstream::open.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

35 posts views Thread by whisper | last post: by
13 posts views Thread by Sunil | last post: by
41 posts views Thread by Miguel Dias Moura | last post: by
37 posts views Thread by eoindeb | last post: by
1 post views Thread by ank | last post: by
2 posts views Thread by ank | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.