Thursday, March 9, 2017

Digest for comp.lang.c++@googlegroups.com - 25 updates in 8 topics

Christopher Pisz <christopherpisz@gmail.com>: Mar 09 09:27AM -0800

It seems to me there is a subtle problem with the following code:
 
 
 
#include <atomic>
 
class State
{
public:
enum ServiceState
{
STOPPING = 0
, STOPPED
, STARTING
, STARTED
};
 
State(State::ServiceState initialState);
 
ServiceState GetState() const;
void SetState(ServiceState state);
 
private:
 
std::atomic<ServiceState> m_state;
};
 
State::State(State::ServiceState initialState)
:
, m_state(initialState)
{
}
 
//----------------------------------------------------------------------------------------
State::ServiceState State::GetState() const
{
return m_state;
}
 
//----------------------------------------------------------------------------------------
void State::SetState(ServiceState state)
{
// TODO - Log the state change
 
m_state = state;
}
 
 
 
int main()
{
State state(State::STARTED);
 
// TODO - State can chnange between OR comparisons
// The encapsulation of the atomic object destroyed the guarentee
// that a comparison of an atomic with a single value would provide
//
// On the otherhand, I am not sure how you would get the same behavior
// from the atomic that you would get with
//
// enum State{STOPPING = 0, STOPPED, STARTING, STARTED};
//
// bool running = false;
// {
// std::lock_guard<std::mutex> lock();
// running = (state == State::STARTED || state == State::STARTING)
// }
//
// if( running ) { //do stuff }
//
if (state.GetState() == State::STARTED || state.GetState() == State::STARTING)
{
// Do stuff
}
 
return 0;
}
 
 
 
As I describe in the todo before the comparison. I am thinking about wta happens when we compare with multiple values in ORed like that. One comparison occurs at a time, so we re no longer really atomic.
 
Is there a way to get fix and still encapsulate atomic, or do we need to go back to using a lock and mutex when comparing multiple values like that?
scott@slp53.sl.home (Scott Lurndal): Mar 09 05:47PM

> // if( running ) { //do stuff }
> //
> if (state.GetState() == State::STARTED || state.GetState() == State::STARTING)
 
if (state.is_state(State::STARTED|State::STARTING)) {
...
}
 
 
bool State::is_state(int flags) const { return (int)m_state.load() & flags; }
Marcel Mueller <news.5.maazl@spamgourmet.org>: Mar 09 07:25PM +0100

On 09.03.17 18.27, Christopher Pisz wrote:
> std::atomic<ServiceState> m_state;
[...]
> // TODO - Log the state change
 
> m_state = state;
> }
 
std::atomic is of no particular use in your code since anyone can do any
state change at any time.
 
Normally a state machine should control /valid/ state changes.
 
 
> // TODO - State can chnange between OR comparisons
> // The encapsulation of the atomic object destroyed the guarentee
> // that a comparison of an atomic with a single value would provide
 
Agreed. But the result is undefined anyway since the state can change
/before/ the condition as well.
 
> // std::lock_guard<std::mutex> lock();
> // running = (state == State::STARTED || state == State::STARTING)
> // }
 
#1:
State l_state = state;
running = l_state == State::STARTED || l_state == State::STARTING;
 
#2
running = state >= State::STARTING;
 
> // Do stuff
> }
 
> As I describe in the todo before the comparison. I am thinking about wta happens when we compare with multiple values in ORed like that. One comparison occurs at a time, so we re no longer really atomic.
 
That's true. But it does not make any difference in your code because at
"Do stuff" state is undefined anyway since it can change at /any/ time
not just between the comparisons.
 
 
> Is there a way to get fix and still encapsulate atomic, or do we need to go back to using a lock and mutex when comparing multiple values like that?
 
The comparison is not your problem. The code at DoStuff probably need to
be synchronized with state changes.
 
 
Marcel
Christopher Pisz <christopherpisz@gmail.com>: Mar 09 11:01AM -0800

On Thursday, March 9, 2017 at 11:27:21 AM UTC-6, Christopher Pisz wrote:
 
> As I describe in the todo before the comparison. I am thinking about wta happens when we compare with multiple values in ORed like that. One comparison occurs at a time, so we re no longer really atomic.
 
> Is there a way to get fix and still encapsulate atomic, or do we need to go back to using a lock and mutex when comparing multiple values like that?
 
 
 
 
For clarity let me change the code using a mutex and lock that we are comparing against. The original way in comments using a mutex really has the same problem. In the end, I want to ensure the state does not change while comparing state against multiple possible states.
 
/* Alternate way using mutex*/
std::unique_lock<std::mutex> lock(g_mutex);
while (g_state == ServiceState::STARTED || g_state == ServiceState::STARTING)
{
lock.unlock();
 
// Do Stuff
 
lock.lock();
}
 
lock.unlock();
red floyd <dont.bother@its.invalid>: Mar 08 03:30PM -0800

On 3/8/2017 1:56 PM, Mike Copeland wrote:
> even more field names, and any field can be in any column of the file.
> 8<{{
> Does this help?
 
 
std::map<std::string,std::function> ?
Manfred <invalid@invalid.add>: Mar 09 01:35AM +0100

On 03/09/2017 12:30 AM, red floyd wrote:
>> 8<{{
>> Does this help?
 
> std::map<std::string,std::function> ?
 
I think a static std::map<std::string,std::function> (indeed) that maps
field names to field handlers.
Then also a dynamic std::map<int,std::function> that maps field indices
to field handlers.
Alternatively a dynamic std::map<int,std::string> that maps field
indices to field names, and then find the handlers via the static map -
obviously less efficient.
"Alf P. Steinbach" <alf.p.steinbach+usenet@gmail.com>: Mar 09 10:31AM +0100

On 08-Mar-17 10:56 PM, Mike Copeland wrote:
> even more field names, and any field can be in any column of the file.
> 8<{{
> Does this help?
 
Yes, much more clear what you're after.
 
Here's some code that might help:
 
 
#include <exception> // std::runtime_error
#include <string> // std::string
#include <unordered_map> // std::unordered_map
#include <vector> // std::vector
 
namespace mc {
using std::string;
using std::to_string;
using std::vector;
 
using X = std::runtime_error;
 
template< class Key, class Value >
using Map_ = std::unordered_map<Key, Value>;
 
struct Col_id
{
enum Enum { dp, bn, op, fn, _ };
static constexpr int n_values = _;
};
 
inline auto operator++( Col_id::Enum& e )
-> Col_id::Enum&
{
e = Col_id::Enum( e + 1 );
return e;
}
 
struct Named_offset{ string name; int value; };
using Col_offsets = Map_<Col_id::Enum, Named_offset>;
 
class Col_names
{
private:
Map_<string, Col_id::Enum> items_;
 
public:
auto id_for( string const& name ) const
-> Col_id::Enum
{
auto const it = items_.find( name );
if( it == items_.end() )
{
throw X{ "Col_names: no such name as `" + name + "`" };
}
return it->second;
}
 
Col_names()
{
items_ =
{
{ "NO.", Col_id::bn },
{ "BIB", Col_id::bn },
{ "PLACE", Col_id::op },
{ "OPLACE", Col_id::op },
{ "OVERALL_RANK", Col_id::op },
{ "TEAMPLACE", Col_id::op },
{ "FIRST NAME", Col_id::fn }
};
}
};
 
// This is a Meyers' singleton:
inline auto col_names()
-> Col_names const&
{
static Col_names const the_names;
return the_names;
}
 
inline auto offsets_from( vector<string> const& col_headers )
-> Col_offsets
{
Col_offsets result;
int offset = 0;
for( string const& name : col_headers )
{
Col_id::Enum const id = col_names().id_for( name );
auto const pair = result.insert( {id, Named_offset{ name,
offset} } );
bool const was_inserted = pair.second;
if( not was_inserted )
{
string const description = name + "` -> " + to_string(
id );
throw X{ "offsets_from: duplicate id, `" + description };
}
++offset;
}
return result;
}
 
} // namespace mc
 
#include <iostream> // std::cout etc.
#include <stdlib.h> // EXIT_FAILURE, EXIT_SUCCESS
using namespace std;
 
void cpp_main()
{
vector<string> const col_headers = { "BIB", "FIRST NAME",
"TEAMPLACE" };
 
cout << "Names:";
for( string const& name : col_headers )
{
cout << " `" << name << "`";
}
cout << endl;
 
mc::Col_offsets const offsets = mc::offsets_from( col_headers );
 
using Id = mc::Col_id;
 
cout << "Offsets:";
vector<Id::Enum> missing;
for( Id::Enum id{}; id < Id::n_values; ++id )
{
try
{
mc::Named_offset const& offset = offsets.at( id );
cout << " " << offset.name << "->" << offset.value;
}
catch( ... )
{
missing.push_back( id );
}
}
cout << endl;
cout << missing.size() << " known columns were not present";
if( missing.size() == 0 )
{
cout << "." << endl;
}
else
{
cout << ", namely (id)";
for( Id::Enum const id : missing )
{
cout << " " << id;
}
cout << "." << endl;
}
}
 
auto main()
-> int
{
try
{
cpp_main();
return EXIT_SUCCESS;
}
catch( exception const& x )
{
cerr << "!" << x.what() << endl;
}
return EXIT_FAILURE;
}
 
 
Cheers!,
 
- Alf
scott@slp53.sl.home (Scott Lurndal): Mar 09 01:51PM

>address is in the table. Something like:
 
> {"NO.", &BNoffset, "BIB", &BNoffset, "PLACE", &OPoffset, etc. }
 
> Is such a thing available in C++? If so, how is it coded and used?
 
If you can do it in C, you can do it in C++, the same way. Consider
a class as a struct and use offset_of to store the offset of the
class/struct data member in the array.
 
# define OFFSET_OF(struct, member) \
((size_t)(&(reinterpret_cast<struct*>(__alignof__(struct*)))->member) - \
__alignof__(struct*))
 
/**
* Describe the "location" of each of the registers named above in the
* current guest. The entries in this table should be ordered
* consistent with the register enumeration and regnames tables.
*/
static struct _reglist guestregs[] = {
{ OFFSET_OF(user_regs_t, rax), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, rbx), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, rcx), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, rdx), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, rsp), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, rbp), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, rsi), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, rdi), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, r8 ), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, r9 ), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, r10), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, r11), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, r12), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, r13), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, r14), sizeof(uint64), BASE_URP },
{ OFFSET_OF(user_regs_t, r15), sizeof(uint64), BASE_URP },
{ OFFSET_OF(vmcb_t, rip), sizeof(uint64), BASE_VMCB },
{ OFFSET_OF(vmcb_t, rflags), sizeof(uint64), BASE_VMCB },
{ OFFSET_OF(vmcb_t, ss.selector), sizeof(uint16), BASE_VMCB },
{ OFFSET_OF(vmcb_t, cs.selector), sizeof(uint16), BASE_VMCB },
{ OFFSET_OF(vmcb_t, exit_code)+4, sizeof(uint32), BASE_VMCB },
{ OFFSET_OF(vmcb_t, exit_info1)+4, sizeof(uint32), BASE_VMCB },
{ OFFSET_OF(vmcb_t, cr0), sizeof(uint64), BASE_VMCB },
{ OFFSET_OF(vmcb_t, cr2), sizeof(uint64), BASE_VMCB },
{ OFFSET_OF(vmcb_t, cr3), sizeof(uint64), BASE_VMCB },
{ OFFSET_OF(vmcb_t, cr4), sizeof(uint64), BASE_VMCB },
{ 0, sizeof(uint64), BASE_DR },
{ 1, sizeof(uint64), BASE_DR },
{ 2, sizeof(uint64), BASE_DR },
{ 3, sizeof(uint64), BASE_DR },
{ 4, sizeof(uint64), BASE_DR },
{ 5, sizeof(uint64), BASE_DR },
{ OFFSET_OF(vmcb_t, dr6), sizeof(uint64), BASE_VMCB },
{ OFFSET_OF(vmcb_t, dr7), sizeof(uint64), BASE_VMCB },
};
 
switch (rp->r_base) {
case BASE_URP:
base = urp;
break;
case BASE_VMCB:
base = vp;
break;
...
}
 
switch (rp->r_len) {
case sizeof(uint64_t):
contents = getu64((uint64)base + rp->r_offset);
break;
case sizeof(uint32_t):
contents = getu32((uint64)base + rp->r_offset);
break;
case sizeof(uint16_t):
contents = getu16((uint64)base + rp->r_offset);
break;
case sizeof(uint8_t):
contents = getu8((uint64)base + rp->r_offset);
break;
}
 
/**
* Return an unsigned 16-bit quantity from the designed address.
* Returns the value zero if the address couldn't be validated.
*
* @param addr The address from which to fetch the word
* @returns the word value at address, or zero if address isn't valid
*/
inline uint16_t
c_debugger::getu16(uint64_t addr)
{
if (check(addr, sizeof(uint16_t))) return *(uint16_t *)addr;
return 0;
}
 
(This code is from a bare-metal hypervisor written in C++)
Mike Copeland <mrc2323@cox.net>: Mar 09 09:44AM -0700

In article <o9r791$s2k$1@dont-email.me>,
alf.p.steinbach+usenet@gmail.com says...
> > each data field in data record so that I know how to process the data
> > values. For example, if Column 2 has the "BIB" values, I want to
> > process that data with a routine that's coded for whatever the
 
Wow, that's much more than I can understand! (My failure)
I've tried the following:
 
std::map<std::string, int> csvMap;
std::string temp = "BIB";
int BNoffset;
csvMap[temp] = BNoffset;
csvMap[temp] = &BNoffset;
csvMap[temp] = *BNoffset;
csvMap["NO."] = BNoffset;
 
none of compiles. I've tried variations (*int, &int, *BNoffset,
&BNoffset) without success. I cannot store a map object with a string
data variable, so I can't store an integer value in the std::map object.
Please advise. TIA

 
---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus
Paavo Helde <myfirstname@osa.pri.ee>: Mar 09 08:48PM +0200

On 9.03.2017 18:44, Mike Copeland wrote:
> csvMap["NO."] = BNoffset;
 
> none of compiles. I've tried variations (*int, &int, *BNoffset,
> &BNoffset) without success.
 
The following compiles for me fine. Either you are not posting your real
code, or you have messed something else up. Please post real code and
include error messages!
 
#include <map>
#include <string>
int main() {
std::map<std::string, int> csvMap;
std::string temp = "BIB";
int BNoffset = 42;
csvMap[temp] = BNoffset;
csvMap["NO."] = BNoffset;
}
kushal bhattacharya <bhattacharya.kushal4@gmail.com>: Mar 08 08:59PM -0800

I am thinking of storing those threds in a list and then accessing them when its really necessary to access those threads and check for whether those threads are doing any current job or not
kushal bhattacharya <bhattacharya.kushal4@gmail.com>: Mar 09 04:47AM -0800

could anyone please point me some reference in order to acheive this?
Paavo Helde <myfirstname@osa.pri.ee>: Mar 09 03:56PM +0200

On 9.03.2017 14:47, kushal bhattacharya wrote:
> could anyone please point me some reference in order to acheive this?
 
http://lmgtfy.com/?q=c%2B%2B+thread+pool+library+example
wij@totalbb.net.tw: Mar 09 06:13AM -0800

On Thursday, March 9, 2017 at 8:47:51 PM UTC+8, kushal bhattacharya wrote:
> could anyone please point me some reference in order to acheive this?
 
Yes, it looks you just need another thread or so because codes
would be cleaner and easier to maintain, such little resource
consumption probably not something to concern about in reality.
 
I am not trouble myself with std:: things, can't give you reference,
and as I know, C++ has no documentation for general application users.
kushal bhattacharya <bhattacharya.kushal4@gmail.com>: Mar 09 09:46AM -0800

hi,
this may look silly but i have searched about it and i am slightly confused whether the approach i looked is suitable for me or not so i was asking about better references here
Paavo Helde <myfirstname@osa.pri.ee>: Mar 09 08:39PM +0200

On 9.03.2017 19:46, kushal bhattacharya wrote:
> hi,
> this may look silly but i have searched about it and i am slightly confused whether the approach i looked is suitable for me or not so i was asking about better references here
 
You need to learn how to reply to correct messages and how to quote
previous messages. I guess by now everybody has already forgotten what
problems you are trying to solve and what approach you are trying to
take (assuming that somebody understood it in the first place).
Mark Storkamp <mstorkamp@yahoo.com>: Mar 09 10:02AM -0600

I'm somewhat familiar with c, but not so much with c++. I'm writing a
program for an Arduino micro-processor board, and the environment is c++.
 
For serial communication I generally use the Serial class. There are
calls such as: Serial.open(), Serial.print(), Serial.println(), etc.
 
Sometimes my code goes on to an Arduino ProMicro board, and then instead
of the Serial class I need to use the Serial1 class, e.g.
Serial1.open(), Serial1.print(), etc.
 
Fortunately the compiler does #define ARDUINO_AVR_PROMICRO when I'm
using the ProMicro board. So everywhere I do serial I/O I could do:
 
#ifdef ARDUINO_AVR_PROMICRO
Serial1.print(...); // or .open, or .println etc
#else
Serial.print(...);

No comments: