Boost shared_ptr issue with TR1 libraries - boost

class MyClass{
public:
MyClass() {}
virtual ~MyClass() {}
};
extern "C" int foo(int tryNumber)
{
std::tr1::shared_ptr<MyClass> myClass(new MyClass());
std::cout << "Object has been created " << tryNumber << << std::endl;
return 0;
}
Then somewhere in my program I write:
for (int i = 0; i < 10000; ++i){
foo(i);
}
There are the facts:
1) gcc 4.0.1, and I can't update them yet. So when I implement std::tr1::shared_ptr, I see the complier uses boost/shared_ptr.hpp (boost 1.33.1)
2) Well, the program uses many threads, I even don't know how they do work and what they do completely (the large project at my job), but I know, that I don't use any shared variables or something else that can cause this behavior
3) Sometimes it just prints:
Object has been created 0
Object has been created 1
...
Object has been created 9999
And everything is ok
Sometimes it prints 0-1-2-3-4 (or more) lines and then stops. Furthermore - I know, that the object has been created, but function hasn't returned the value and program just freezes, and when I try to attach to the program with gdb and type "where" - I see this:
0) 0xb7fd8430 in __kernel_vsyscall ()
1) 0xb7d9bece in _lll_mutex_lock-wait() from /lib/i686/libpthread.so.0
2) 0xb7d98500 in _L_mutex_lock_71 () from /lib/i686/libpthread.so.0
3) 0xbfbefab8 in ?? ()
4) 0x00000000 in ?? ()
Or this:
0) 0xb7fd8430 in __kernel_vsyscall ()
1) 0xb7d9bece in _lll_mutex_lock-wait() from /lib/i686/libpthread.so.0
2) 0xb7d98500 in _L_mutex_lock_71 () from /lib/i686/libpthread.so.0
..dunno what is here, I see only " .. in ?? ()"
10) .. in __gthread_mutex_lock
11) .. in __gthread_mutex_lock
12) .. in std::tr1::_Sp_counted_base::release
13) .. in ~shared_count
14) .. in ~shared_ptr
Seems it like shared_ptr is broken?

I just solved this issue. Changed this:
#include <tr1/memory> to #include <boost/shared_ptr.hpp>
std::tr1::shared_ptr to boost::shared_ptr
The solution is described here link

Related

sigsegv Using MessageDifferencer on proto messages

I am a novice trying to use google protobuf for work project. I want to find out difference between protobuf messages and hence trying to use the MessageDifferencer APIs. I get the SEGV while running the code below. Commenting the line "reporter->ReportModified(*Obj1, *Obj2, field_path);" results in no segv
Any help in usage of differencer appreciated!
google::protobuf::util::MessageDifferencer diff;
diff.set_report_matches(false);
diff.set_report_moves(false);
std::string reportDiff;
google::protobuf::io::StringOutputStream* opstream = new google::protobuf::io::StringOutputStream(&reportDiff);
google::protobuf::util::MessageDifferencer::StreamReporter* reporter = new google::protobuf::util::MessageDifferencer::StreamReporter(opstream);
diff.ReportDifferencesTo(reporter);
std::vector<google::protobuf::util::MessageDifferencer::SpecificField> field_path;
try
{
reporter->ReportModified(*Obj1, *Obj2, field_path);
}
catch (const std::exception& e)
{
std::cout << e.what() <<"\n";
}
cout << __func__ << " Report added " << field_path.size();
//Cleanup objects
delete Obj1;
delete Obj2;
delete reporter;
Thanks,
Maddy
You shouldn't be calling the ReportModified method directly, the MessageDifferencer class calls it when it finds a difference.
MessageDifferencer::Compare is the correct method to call, according to the docs. Assuming all else is correct, I believe changing your code inside the try-loop to call that should work.
Moving your code to a function, you could have something like
std::string CompareMessages(
const google::protobuf::Message& m1,
const google::protobuf::Message& m2) {
using google::protobuf::util::MessageDifferencer;
MessageDifferencer diff;
diff.set_report_matches(false);
diff.set_report_moves(false);
std::string reportDiff;
{
google::protobuf::io::StringOutputStream opstream(&reportDiff);
MessageDifferencer::StreamReporter reporter(&opstream);
diff.ReportDifferencesTo(&reporter);
diff.Compare(m1, m2);
}
return std::move(reportDiff);
}

C++11 std::condition_variable - notify_one() not behaving as expected?

I don't see this program having any practical usage, but while experimenting with c++ 11 concurrency and conditional_variables I stumbled across something I don't fully understand.
At first I assumed that using notify_one() would allow the program below to work. However, in actuality the program just froze after printing one. When I switched over to using notify_all() the program did what I wanted it to do (print all natural numbers in order). I am sure this question has been asked in various forms already. But my specific question is where in the doc did I read wrong.
I assume notify_one() should work because of the following statement.
If any threads are waiting on *this, calling notify_one unblocks one of the waiting threads.
Looking below only one of the threads will be blocked at a given time, correct?
class natural_number_printer
{
public:
void run()
{
m_odd_thread = std::thread(
std::bind(&natural_number_printer::print_odd_natural_numbers, this));
m_even_thread = std::thread(
std::bind(&natural_number_printer::print_even_natural_numbers, this));
m_odd_thread.join();
m_even_thread.join();
}
private:
std::mutex m_mutex;
std::condition_variable m_condition;
std::thread m_even_thread;
std::thread m_odd_thread;
private:
void print_odd_natural_numbers()
{
for (unsigned int i = 1; i < 100; ++i) {
if (i % 2 == 1) {
std::cout << i << " ";
m_condition.notify_all();
} else {
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock);
}
}
}
void print_even_natural_numbers()
{
for (unsigned int i = 1; i < 100; ++i) {
if (i % 2 == 0) {
std::cout << i << " ";
m_condition.notify_all();
} else {
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock);
}
}
}
};
The provided code "works" correctly and gets stuck by design. The cause is described in the documentation
The effects of notify_one()/notify_all() and
wait()/wait_for()/wait_until() take place in a single total order, so
it's impossible for notify_one() to, for example, be delayed and
unblock a thread that started waiting just after the call to
notify_one() was made.
The step-by-step logic is
The print_odd_natural_numbers thread is started
The print_even_natural_numbers thread is started also.
The m_condition.notify_all(); line of print_even_natural_numbers is executed before than the print_odd_natural_numbers thread reaches the m_condition.wait(lock); line.
The m_condition.wait(lock); line of print_odd_natural_numbers is executed and the thread gets stuck.
The m_condition.wait(lock); line of print_even_natural_numbers is executed and the thread gets stuck also.

lambda captures; c++ vs elisp

Reading the answer from Capturing a reference by reference in a C++11 lambda makes me think that the following code generates undefined behavior because of the ended lifetime of i in the lambda-capture. Is that right for C++1y? I am asking because g++ 4.8.2 translates the code just fine.
#include <iostream>
auto captureFct( ) {
int i=0;
auto set = [&i](int _i){ i=_i; };
auto get = [&i](){ return i; };
return std::pair<decltype(set),decltype(get)>(set,get);
}
int main() {
auto myPair = captureFct();
auto set1 = myPair.first;
auto get1 = myPair.second;
auto myPair1 = captureFct();
auto set2 = myPair1.first;
auto get2 = myPair1.second;
std::cout << "\nget1:" << get1() << " get2:" << get2() << '\n';
set1(1); set2(2);
std::cout << "\nget1:" << get1() << " get2:" << get2();
}
/*
Local Variables:
compile-command: "g++ -std=c++1y lambda.cc -o a.exe && ./a.exe"
End:
*/
The output is interesting:
get1:0 get2:0
get1:2 get2:2
It seems that the same reference is used for all lambdas.
This behavior differs from the behavior of the following elisp code (as close to the c++ code as possible):
(defun captureFct ()
(lexical-let ((i 0))
(list :set (lambda (_i) (setq i _i))
:get (lambda () i))))
(setq myPair (captureFct))
(setq myPair1 (captureFct))
(message "\nget1: %d get2: %d"
(funcall (plist-get myPair :get))
(funcall (plist-get myPair1 :get)))
(funcall (plist-get myPair :set) 1)
(funcall (plist-get myPair1 :set) 2)
(message "\nget1: %d get2: %d"
(funcall (plist-get myPair :get))
(funcall (plist-get myPair1 :get)))
The output of the elisp code is:
get1: 0 get2: 0
get1: 1 get2: 2
I think I know already the answer. But, I post this question anyway since it is interesting for folks that do both elisp and c++.
Last but not least a C++ version that works like the elisp version:
#include <iostream>
#include <memory>
auto captureFct( ) {
std::shared_ptr<int> pi(new int(0));
auto set = [pi](int _i){ *pi=_i; };
auto get = [pi](){ return *pi; };
return std::pair<decltype(set),decltype(get)>(set,get);
}
int main() {
auto myPair = captureFct();
auto set1 = myPair.first;
auto get1 = myPair.second;
auto myPair1 = captureFct();
auto set2 = myPair1.first;
auto get2 = myPair1.second;
std::cout << "\nget1:" << get1() << " get2:" << get2() << '\n';
set1(1); set2(2);
std::cout << "\nget1:" << get1() << " get2:" << get2();
}
/*
Local Variables:
compile-command: "g++ -std=c++1y lambda.cc -o a.exe && ./a.exe"
End:
*/
Yes, it's undefined behaviour, since the references inside the lambdas become dangling as soon as captureFunc() exits (*).
What's probably happening in your case is that the references (which are just pointers under the hood) still point to the space on the stack where i was on the first invocation of captureFunc(), and it ends up in exactly the same location on the second invocation of captureFunc(); so the net effect is that all of get1, get2, set1, set2 have their internal i reference pointed to the same (currently unused) location in memory, so they modify it for each other.
Of course, the above is just speculation, and could change next time you (or run) the program, since Undefined Behaviour is Undefined.
(*) Quoting C++11, [expr.prim.lambda]§22:
[ Note: If an entity is implicitly or explicitly captured by reference, invoking the function call operator of
the corresponding lambda-expression after the lifetime of the entity has ended is likely to result in undefined
behavior. —end note ]

How to record the running information of functions in your program?

I recently attended a coding interview and I was asked a question which I didn't know the answer to. After searching the answer on the internet for a few day, I come here call for help.
The question is described as followed: You should propose a approach to record the running information of function in your program, for example, the times of a function called, and so on.
By the way, you are not allowed to modify these functions. Maybe you want to define a global variant in these function to record the running function, but that is not allowed.
Ok! That's all about the question I met in a coding interview.
This is the best I could come up with using C++ macros. I don't know whether it conforms to the requirements.
A very basic version just recording the count. The macro replaces all existing calls to the function with the contents of the macro, which records the stats and calls the function. Can easily be extended to record more details. Assumes there's only one function with that name or you want one count for all of them. Requires a macro for each function.
// here's our function
void func()
{ /* some stuff */ }
// this was added
int funcCount = 0;
#define func(...) do { funcCount++; func(__VA_ARGS__); } while(0)
int main()
{
// call the function
func();
// print stats
cout << funcCount << endl;
return 0;
}
Prints 1.
A more generic version. Requires changes to how the function is called.
// here are our functions
void someFunc()
{ /* some stuff */ }
void someOtherFunc()
{ /* some stuff */ }
// this was added
map<string, int> funcCounts;
#define call(func, ...) do { funcCounts[ #func ]++; func(##__VA_ARGS__); } while(0)
int main()
{
// call the functions
// needed to change these from 'someFunc();' format
call(someFunc);
call(someOtherFunc);
call(someFunc);
// print stats
for (map<string, int>::iterator i = funcCounts.begin(); i != funcCounts.end(); i++)
cout << i->first << " - " << i->second << endl;
return 0;
}
Prints:
someFunc - 2
someOtherFunc - 1

How can I do that without WIN32 API?

So, here is a countdown.
My aim is the next: if you don't do anything for the given time (ent_sec) the countdown will reach 0 after a time and return with 0, BUT if you press down the letter c (code: 99) the countdown stops and you can enter your PIN code and return with it.
I have already solved the problem with Windows.h in the next way:
if (GetAsyncKeyState(VK_SPACE))
This solves the problem is through WIN32 API (in this case you have to press SPACE, not letter 'c'), but it revealed that I can't use any WinAPI function (school project). So I rewrite this line to the following:
if (getchar() == 99)
But unfortunately it doesn't work in the proper way, cause my countdown stops in almost every second until I dont't press some "wrong" key (for example I press 'x', then the countdown goes forward, but in the next sec it stops again)... In the first solution (win func) this problem doesn't exist... So how can I fix that? Thanks. Here is the whole code of my function:
unsigned Timer::DownCount
{
int ent_sec = this.time;
cout << "The counter has started (" << this.time << "sec), press 'C' to enter your PIN code: " << endl;
while (ent_sec >= 0)
{
if (getchar() == 99) // c letter's code is 99 in ANSI (or ASCII dunno)
{
unsigned code;
cout << "PIN code: ";
cin >> code;
return code;
}
else
{
SecCounter(1); // this function counts 1 secundum
cout << ent_sec << endl;
ent_sec--;
}
}
return 0;
}
I don't believe there's a standard way to do this that will work across all platforms, but here's one way of doing it that will work on Windows without actually using Windows API functions.
int getch_nowait()
{
if (!kbhit()) return -1;
return getch();
}
Then your check just becomes if (getch_nowait() == 99) ...
This code may be compiler specific. If it doesn't work for you, it'll help if you tell us what compiler and operating system you are using.

Resources