473,574 Members | 2,350 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static member variable in multithreaded environment

I tried searching the newgroups for an answer to this question. I
found
many related topics, but didn't find the exact answer I am looking
for.
I am implementing a class to aid in the logging for our product as
follows. Code snippet is as follows.

//Header file srvLog.h starts here
enum eErrLvl
{
eLOG_DEBUG_5 = 1,
eLOG_DEBUG_4,
eLOG_DEBUG_3,
eLOG_DEBUG_2,
eLOG_DEBUG_1,
eLOG_INFO,
eLOG_WARNING,
eLOG_ERROR,
eLOG_FATAL
};

std::ostream& operator << (std::ostream&, eErrLvl&);

class srvLog
{
static int nLglvl;
eErrLvl nSeverity;
public:
srvLog () {}
static void setlvl (int lvl) { nLglvl = lvl; }
const srvLog& operator () (eErrLvl nSvrty) { nSeverity =
nSvrty; return *this;}
friend std::ostream& operator << (std::ostream& , const
srvLog&);
};

//Source file srvLog.C starts here
int srvLog::nLglvl = eLOG_ERROR;

std::ostream&
operator << (std::ostream& os, eErrLvl& eLvl)
{
switch (eLvl)
{
case eLOG_DEBUG_5:
case eLOG_DEBUG_4:
case eLOG_DEBUG_3:
case eLOG_DEBUG_2:
case eLOG_DEBUG_1:
os << "Debug\t: ";
break;
case eLOG_INFO:
os << "Info\t: ";
break;
case eLOG_WARNING:
os << "Warn\t: ";
break;
case eLOG_ERROR:
os << "Error\t: ";
break;
case eLOG_FATAL:
os << "Fatal\t: ";
break;
}
return os;
}
std::ostream& operator << (std::ostream& os, const srvLog& oLog)
{
if (oLog.nSeverity >= oLog::nLglvl)
os.clear();
else
{
os.clear (std::ios::fail bit);
return os;
}
char msg[100];
//memset (msg, '\0', 100);
struct timeval now;
gettimeofday (&now, NULL);

struct tm *pTm = localtime (&now.tv_sec) ;
strftime (msg, 100, "%c ", pTm);
os << msg << oLog.nSeverity;
return os;
}
//Sample use case

int main ()
{
srvLog lgstrt;
//Class A
A ainst;
std::cerr << lgstrt(eLOG_FAT AL) << "more to log " << ainst <<
std::endl;
pthread_create (, threadA, ... , ...);
pthread_create (, threadB, ... , ...);

}
//ThreadA in a different file and shared library
void threadA ()
{
srvLog lgstrt;
//Class A
A ainst;
std::cerr << lgstrt(eLOG_FAT AL) << "more to log " << ainst <<
std::end;
}

//ThreadB in a different file and shared library
void threadB ()
{
srvLog lgstrt;
//Class A
A ainst;
std::cerr << lgstrt(eLOG_FAT AL) << "more to log " << ainst <<
std::endl;
}

Logging is controlled by the nLglvl static variable. This is part of
a daemon. So the logging is to a file and the value of nLglvl will be
set by a command line tool.
My questions are the following
1) Is the value of nLglvl shared by threadA, threadB and main()
thread.

2)Where should I call setlvl()?
3) If the answer to 1) is yes. Is it really required to use locking
in
this scenario. Because the change to the value of nLglvl will be
infrequent and I can live with some bad reads.

I am using POSIX threads. Linux and solaris are the current
environments. It must be portable to all unix flavors. I threads are
not part of the C++ standard, but to me it does n't make much sense. I
feel this is as much a C++ question as a Threads one

Ninan

Jul 23 '05 #1
1 2219
nin234 wrote:
I tried searching the newgroups for an answer to this question.
I found many related topics
but didn't find the exact answer I am looking for.
I am implementing a class
to aid in the logging for our product as follows.
Code snippet is as follows. cat srvLog.h #ifndef GUARD_SRVLOG_H
#define GUARD_SRVLOG_H 1

#include <iostream>

//Header file srvLog.h starts here
enum eErrLvl {
eLOG_DEBUG_5 = 1,
eLOG_DEBUG_4,
eLOG_DEBUG_3,
eLOG_DEBUG_2,
eLOG_DEBUG_1,
eLOG_INFO,
eLOG_WARNING,
eLOG_ERROR,
eLOG_FATAL
};

std::ostream& operator<<(std: :ostream&, const eErrLvl&);

class srvLog {
private:
static int nLglvl;
eErrLvl nSeverity;
public:
srvLog(void) { }
static void setlvl(int lvl) { nLglvl = lvl; }
const srvLog& operator()(eErr Lvl nSvrty) {
nSeverity = nSvrty;
return *this;
}
friend
std::ostream& operator<<(std: :ostream&, const srvLog&);
};

class A {
public:
friend
std::ostream& operator<<(std: :ostream& os, const A& a) {
return os << 13;
}
};

#endif//GUARD_SRVLOG_H
cat srvLog.C //Source file srvLog.C starts here
#include <sys/time.h>
#include "srvLog.h"

int srvLog::nLglvl = eLOG_ERROR;

std::ostream&
operator<<(std: :ostream& os, const eErrLvl& eLvl) {
switch (eLvl) {
case eLOG_DEBUG_5:
case eLOG_DEBUG_4:
case eLOG_DEBUG_3:
case eLOG_DEBUG_2:
case eLOG_DEBUG_1:
os << "Debug\t: ";
break;
case eLOG_INFO:
os << "Info\t: ";
break;
case eLOG_WARNING:
os << "Warn\t: ";
break;
case eLOG_ERROR:
os << "Error\t: ";
break;
case eLOG_FATAL:
os << "Fatal\t: ";
break;
}
return os;
}

std::ostream&
operator<<(std: :ostream& os, const srvLog& oLog) {
if (oLog.nSeverity >= srvLog::nLglvl) {
os.clear();
char msg[100];
//memset (msg, '\0', 100);
struct timeval now;
gettimeofday(&n ow, NULL);

struct tm* pTm = localtime (&now.tv_sec) ;
strftime (msg, 100, "%c ", pTm);
os << msg << oLog.nSeverity;
}
else {
os.clear (std::ios::fail bit);
}
return os;
}
cat main.C //Sample use case
#include "srvLog.h"
#include <pthread.h>

int main(int argc, char* argv[]) {
srvLog lgstrt;
//Class A
A ainst;
std::cerr << lgstrt(eLOG_FAT AL) << "more to log "
<< ainst << std::endl;
// pthread_create( , threadA, ... , ...);
// pthread_create( , threadB, ... , ...);
return 0;
}

//ThreadA in a different file and shared library
void threadA(void) {
srvLog lgstrt;
//Class A
A ainst;
std::cerr << lgstrt(eLOG_FAT AL) << "more to log "
<< ainst << std::endl;
}

//ThreadB in a different file and shared library
void threadB(void) {
srvLog lgstrt;
//Class A
A ainst;
std::cerr << lgstrt(eLOG_FAT AL) << "more to log "
<< ainst << std::endl;
}
g++ -Wall -ansi -pedantic -o main main.C srvLog.C
./main Wed Feb 23 09:10:23 2005 Fatal : more to log 13
Logging is controlled by the nLglvl static variable.
This is part of a daemon so the logging is to a file
and the value of nLglvl will be set by a command line tool.

My questions are the following

1) Is the value of nLglvl shared
by threadA, threadB and main() thread.
nLglvl is just a global variable in the srvLog namespace.
2) Where should I call setlvl()?
You should rewrite setlvl(int) so that srvLog::nLglvl
is protected by mutual exclusion.
Then you can call it anywhere at any time.
3) If the answer to 1) is yes.
Is it really required to use locking in this scenario?
Practically speaking, yes.
Because the change to the value of nLglvl will be
infrequent and I can live with some bad reads.
You say that now ...
I am using POSIX threads.
Linux and Solaris are the current environments.
It must be portable to all UNIX flavors.
I [know that] threads are not part of the C++ standard
but, to me, it doesn't make much sense.
I feel this is as much a C++ question as it is a threads question.


The only C++ question is about the static (global) variable nLglvl.
Now, you would be *much* better off to post your other questions
(about where to call srvLog::setlvl( int), portability, etc.)
in one of the UNIX newsgroups.
Jul 23 '05 #2

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

Similar topics

9
1970
by: Simon Harvey | last post by:
Hi all, In my project I have made a number of helper methods static. As I understand it, this will create the problem that multiple threads could access the static method at the same time and interfere with one another. My question is, for each static method, do I need to lock access to only one call at a time? I've noticed that...
3
1871
by: Bernhard Kick | last post by:
Hi all, I saw this code in the book "Accelerated C++" (chapt 11, iirc): template <class T> class Vec { ... std::allocator<T> alloc; // object to handle memory allocation // ??would static member work here??: // static std::allocator<T> alloc;
2
1716
by: Tryion | last post by:
Hi, I'd like to know if it's possible/responsible to use the ReaderWriterLock class (RWL) in a class without declaring it as "static". The example in the SDK does not use a static RWL. However, the documentation has the standard disclaimer of "Any public static members of this type are safe for multithreaded operations. Any instance...
9
4151
by: Clint | last post by:
Hey all - Excuse the cross-post ... I'm not sure what the appropriate newsgroup would be for this question. I have a question that I'm not quite sure how to ask. For all I know, I have the verbaige completely wrong, but here goes nothing ... I'm currently using the MS Data Access Block for a desktop application I'm writing. Recently, I...
2
2650
by: superseed | last post by:
Hi, I'm pretty new to C#, and I'm quite stuck on the following problem. I would like to add to my application a Windows.Form (singleton) on which I could display a message of one of the following type : Exception, Error, Warning, Infos (with differents colors, etc). I would like to use it like the Console.WriteLine("My Message"); on...
41
10652
by: Miguel Dias Moura | last post by:
Hello, I am working on an ASP.NET / VB page and I created a variable "query": Sub Page_Load(sender As Object, e As System.EventArgs) Dim query as String = String.Empty ... query = String.Format("SELECT * FROM dbo.documents WHERE ") & query End Sub
11
2233
by: dee | last post by:
OleDbCommand class like many .NET classes has the following description in its help file: "Thread Safety Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread safe." I have 2 questions: 1. I thought dynamic variables are thread-safe...
3
2016
by: clqrq | last post by:
i have just a little question: guess i have a class with a static function and i have different threads running. do i have to expect the problem that 2 treads try to acces CA::static() at the same time or does the processor always make shure that one of them has to wait till the other finishes? or may it be that a static func can be...
55
6182
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
0
7828
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...
0
7742
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...
0
8260
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...
0
8127
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...
0
6493
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...
1
5638
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3765
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1362
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1092
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...

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.