By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,159 Members | 992 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,159 IT Pros & Developers. It's quick & easy.

Global vs local streams in a multithreaded app

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.