mercredi 1 juillet 2015

operator << (stream output) for nullptr

Consider a piece of generic C++ code which outputs to a stream the values of its arguments in case they are not equal:

#define LOG_IF_NE(a, b) if(a != b) { \
    std::cerr << "Failed because (" << ##a << "=" << (a) << \
        ") != (" << ##b << "=" << (b) << ")"; \
}

This is just an example, the real code throws an exception after writing message to a string stream. This works fine for 2 integers, 2 pointers, etc. for what stream operator << is defined.

int g_b;
int f(int a)
{
    LOG_IF_NE(a, g_b);
    // implementation follows
}

A problem happens when one of the arguments to LOG_IF_NE is nullptr: MSVC++2013 compiler gives error C2593: 'operator <<' is ambiguous.

int *pA;
int g()
{
    LOG_IF_NE(pA, nullptr);
}

The problem happens because nullptr has a special type and operator << is not defined in the STL for that type. An answer at http://ift.tt/1CJAyzQ suggests to define operator << for std::nullptr_t

//cerr is of type std::ostream, and nullptr is of type std::nullptr_t
std::ostream& operator << (std::ostream& os, std::nullptr_t)
{
    return os << "nullptr"; //whatever you want nullptr to show up as in the console
}

Is it the right way to solve the problem? Isn't it a bug in C++11/STL that operator<< is not defined for nullptr_t? Is a fix expected in C++14/17? Or was it done on purpose (therefore one's private definition of operator<< could have a pitfall)?

c++ max() with intializer list returns strings out of order

max({"a", "b", "z", "x"});  returns "x"

while both

max<std::string>({"a", "b", "z", "x"});

and

max({'a', 'b', 'z', 'x'});

return "z" as they should. Any idea why?

How to make sure all slave threads are waited for conditional variable?

I am running the following chunk of the code. This code is going to create 5 slave threads and 1 main thread. All slave threads are waited for the main thread to make the data ready and when the data gets ready, all slaves will notify to start processing.

My question is, it is possible that before the slave threads start waiting for the conditional_variable, the main thread make the data ready and notify the waited threads. In this case, some threads which were waited will get the notification and start processing but the ones which were not waited, will starting waiting for a notification which will NEVER come.

If you run this example, this case won't happen but I am looking for a way to make sure that all the slave threads are waiting for the notification, then notifying them. Do you know how can I do that?

/*
  Condition Variables - Many waiting threads

  Shows how one condition variable can be used to notify multiple threads
  that a condition has occured.

  * Part of "Threading with Boost - Part IV: Condition Variables", published at:

      http://ift.tt/1dxyAvU

  Copyright (c) 2015 Gavin Baker <gavinb@antonym.org>
  Published under the MIT license, see LICENSE for details
*/

#include <cstdio>

#include <boost/thread.hpp>

boost::condition_variable data_ready_cond;
boost::mutex data_ready_mutex;
bool data_ready = false;

void master_thread()
{
    printf("+++ master thread\n");

    // Pretend to work
    printf("    master sleeping...\n");
    boost::chrono::milliseconds sleepDuration(750);
    boost::this_thread::sleep_for(sleepDuration);

    // Let other threads know we're done
    printf("    master notifying...\n");
    data_ready = true;
    data_ready_cond.notify_all();

    printf("--- master thread\n");
}

void slave_thread(int id)
{
    printf("+++ slave thread: %d\n", id);

    boost::unique_lock<boost::mutex> lock(data_ready_mutex);
    while (!data_ready)
    {
        data_ready_cond.wait(lock);
    }

    printf("--- slave thread: %d\n", id);
}

int main()
{
    printf("Spawning threads...\n");

    boost::thread slave_1(slave_thread, 1);
    boost::thread slave_2(slave_thread, 2);
    boost::thread slave_3(slave_thread, 3);
    boost::thread slave_4(slave_thread, 4);

    boost::thread master(master_thread);

    printf("Waiting for threads to complete...\n");

    slave_1.join();
    slave_2.join();
    slave_3.join();
    slave_4.join();
    master.join();

    printf("Done\n");

    return 0;
}

sleep_for() doesnt work with detached thread

I'm working on application which collects data from GPS receiver with Raspberry Pi and sends signals to camera to take photos. GPS receiver connects to Rapberry via UART so i created monitor class as singleton. Monitor works in detached thread and collects navigation data. Main() collects photos with target frequency. Problem is that sleep_for() doesnt work in main(). Code sample:

void gps_run(uart_monitor* &m)
{
    m->Run();
}

int main()
{
uart_monitor* m = uart_monitor::Instance();
m->Set(Coord, CoordBufMutex);
thread gps_monitor(gps_run,ref(m));
gps_monitor.detach();

    //Test camera shutter
    for (int rep=0; rep<10; rep++)
    {
         GPIO_SET = 1<<GPIO;
         printf("On...\n");
         std::this_thread::sleep_for(std::chrono::milliseconds(300));
         GPIO_CLR = 1<<GPIO;
         printf("Off...\n");
         std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    }

return 0;
}

Programm makes only one "blink" but prints all "On.../Off..." sequence. Whithout gps_monitor thread it works fine.

Wt Segfault on ORM Transaction Commit

http://ift.tt/1C9t8eE says

The complete source code for the examples used in this tutorial are available as ready-to-run programs in the examples/feature/dbo/ folder of Wt.

I'm trying to run tutorial1.C from that directory, and I get the following output:

(gdb) run
Starting program: /home/lawsa/sources/memory/dist/flashcard --docroot . --http-address 0.0.0.0 --http-port 9090
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/libthread_db.so.1".
begin transaction
create table "user" (
  "id" integer primary key autoincrement,
  "version" integer not null,
  "name" text not null,
  "password" text not null,
  "role" integer not null,
  "karma" integer not null
)
commit transaction
created tables
ending transaction

Program received signal SIGSEGV, Segmentation fault.
0x000000000041a4a8 in void std::vector<Wt::Dbo::ptr_base*, std::allocator<Wt::Dbo::ptr_base*> >::emplace_back<Wt::Dbo::ptr_base*>(Wt::Dbo::ptr_base*&&) ()
(gdb) bt
#0  0x000000000041a4a8 in void std::vector<Wt::Dbo::ptr_base*, std::allocator<Wt::Dbo::ptr_base*> >::emplace_back<Wt::Dbo::ptr_base*>(Wt::Dbo::ptr_base*&&) ()
#1  0x0000000000419c8e in std::vector<Wt::Dbo::ptr_base*, std::allocator<Wt::Dbo::ptr_base*> >::push_back(Wt::Dbo::ptr_base*&&) ()
#2  0x0000000000419682 in void Wt::Dbo::Session::implSave<User>(Wt::Dbo::MetaDbo<User>&) ()
#3  0x0000000000418c4e in Wt::Dbo::MetaDbo<User>::flush() ()
#4  0x00007ffff6c8eae2 in Wt::Dbo::Session::flush() ()
   from /usr/lib/libwtdbo.so.38
#5  0x00007ffff6c9d14d in Wt::Dbo::Transaction::Impl::commit() ()
   from /usr/lib/libwtdbo.so.38
#6  0x00007ffff6c9d1a9 in Wt::Dbo::Transaction::commit() ()
   from /usr/lib/libwtdbo.so.38
#7  0x00000000004063d2 in run() ()
#8  0x0000000000407066 in main ()
(gdb)

For your reference, here's my code: http://sprunge.us/PYSO (I hope that lasts for a while, but let me know if it stops working). And my Makefile: http://sprunge.us/UCge and I ran gdb using $ gdb --args ./flashcard --docroot . --http-address 0.0.0.0 --http-port 9090

You can see the output from line 80 but not from 83, and the backtrace from gdb suggests that line 81 (commit) is the problem. If I remove line 81 so that the transaction commits because of going out of scope, the same problem exists, but it comes from the destructor of transaction.

I'm running archlinux with Wt 3.3.4-4, gcc 5.1.0-5, compiling with -std=c++0x.

The only thing I can imagine is if there is some binary incompatibility with std::vector?

object construction : default parameter vs delegation

Consider the following code where I'm trying to introduce a default constructor as well as a parameterized one for class A. This way was introduced in recent c++ improvements.

class A  {
    private:
        unsigned int count;

    public:
        A(int new_c) : count(new_c) {}
        A() : A(10) {}
};

vs the old way of setting a default parameter on parameterized constructor and ignoring the default constructor completely.

class A  {
    private:
        unsigned int count;

    public:
        A(int new_c = 5) : count(new_c) {}
};

Is there any advantage using 1st method over the 2nd one apart from following modern conventions?

implicit parameter in implicit conversion

#include <iostream>
using namespace std;

struct From{
    int i;
    From(){}
};

struct By{
    By(const From& f){}
};

struct To{
    To(const By& b){}
};

int main() {
    From f;
    To to = f;  // error: conversion from 'From' to non-scalar type 'To' requested
    return 0;
}

Is there any way to make this work without modifying By and To ? And also without creating a By object first to convert From