I am trying to use boost channels and fibers in a class. Here is a simple test case which works fine but it is not exactly what I want. If I move "line:1" to "loc:1" the programs hangs (gdb shows at a spinlock inside boost::fibers after c->push(a)). Can anyone help me by pointing what am I doing wrong? Thanks.
Here is the sample code which works and produces the following,
#include <iostream>
#include <boost/fiber/all.hpp>
using namespace std;
template <class T>
class Block
{
private:
typedef boost::fibers::buffered_channel<T> channel_t;
typedef boost::fibers::fiber fiber_t;
fiber_t _thread_send;
fiber_t _thread_recv;
size_t _n;
channel_t* _chan;
public:
Block(size_t n) : _n(n), _chan(nullptr) {
// >>>>>>>>>> loc:1 <<<<<<<<<<<
}
virtual ~Block() {}
void _send(channel_t *c) {
cout << __func__ << endl;
int a = 1000;
cout << "Sending: " << a << endl;
c->push(a);
}
void _recv(channel_t *c) {
cout << __func__ << endl;
int a = 0;
c->pop(a);
cout << "Received: " << a << endl;
}
void do_work() {
cout << "do_work\n";
channel_t temp{_n}; _chan = &temp; // <<<<<<<<<<<< line:1
_thread_send = boost::fibers::fiber(bind(&Block::_send, this, _chan));
_thread_recv = boost::fibers::fiber(bind(&Block::_recv, this, _chan));
_thread_send.join();
_thread_recv.join();
}
};
int main()
{
Block<int> B(2);
B.do_work();
return 0;
}
Output:
do_work
_send
Sending: 1000
_recv
Received: 1000
Compiled using:
GNU/Linux 64 bit x86-64
g++ (GCC) 7.1.1 2017051
boost 1.64.0
g++ -c --std=c++14 -g -Wall -Wpedantic boost_channels.cpp -o boost_channels.o
g++ -lboost_context -lboost_fiber boost_channels.o -o boost_channels
channel_t temp{_n}; _chan = &temp; // <<<<<<<<<<<< line:1
in Block() will not work because temp goes out of scope after leaving Block()'s body and _chan would point to garbage/ freed memory
two versions are possible:
1) keep channel temp a local variable of do_work():
template <class T>
class Block
{
private:
typedef boost::fibers::buffered_channel<T> channel_t;
typedef boost::fibers::fiber fiber_t;
fiber_t _thread_send;
fiber_t _thread_recv;
size_t _n;
public:
Block(size_t n) : _n(n) {
}
virtual ~Block() {}
void _send(channel_t *c) {
cout << __func__ << endl;
int a = 1000;
cout << "Sending: " << a << endl;
c->push(a);
}
void _recv(channel_t *c) {
cout << __func__ << endl;
int a = 0;
c->pop(a);
cout << "Received: " << a << endl;
}
void do_work() {
cout << "do_work\n";
channel_t chan{_n};
_thread_send = boost::fibers::fiber(bind(&Block::_send, this, & chan));
_thread_recv = boost::fibers::fiber(bind(&Block::_recv, this, & chan));
_thread_send.join();
_thread_recv.join();
}
};
2) keep channel temp a member variable of Block<>:
template <class T>
class Block
{
private:
typedef boost::fibers::buffered_channel<T> channel_t;
typedef boost::fibers::fiber fiber_t;
fiber_t _thread_send;
fiber_t _thread_recv;
channel_t _chan;
public:
Block(size_t n) : _chan(n) {
}
virtual ~Block() {}
void _send(channel_t *c) {
cout << __func__ << endl;
int a = 1000;
cout << "Sending: " << a << endl;
c->push(a);
}
void _recv(channel_t *c) {
cout << __func__ << endl;
int a = 0;
c->pop(a);
cout << "Received: " << a << endl;
}
void do_work() {
cout << "do_work\n";
_thread_send = boost::fibers::fiber(bind(&Block::_send, this, & _chan));
_thread_recv = boost::fibers::fiber(bind(&Block::_recv, this, & _chan));
_thread_send.join();
_thread_recv.join();
}
};
both versions generate:
do_work
_send
Sending: 1000
_recv
Received: 1000
When you construct the channel in the Block constructor and take a pointer to it, the pointer _chan is pointing at garbage when temp goes out of scope. You could just make temp a member of Block or leave it where it works so in can be forwarded.
Update:
Brackets(braces) in C++ define scope
Block(size_t n) : _n(n), _chan(nullptr)
//the scope of the constructor starts at this brace
{
//temp gets instantiated
channel_t temp{_n};
//assign the pointer to the object
_chan = &temp;
} //put a break point here
Then use a memory watch to look at _chan. As you move past the closing bracket you should see the memory turn to garbage as temp gets destroyed. If you trace in at that point you will see temp meet its distributor.
I would just leave the temp in do_work.
Ok, declaring channel_t as a member works fine. I guess it is pointing to garbage. Also I learned that boost sync primitives does not like being std::move(ed).
Thanks guys for helping.
Related
I am implementing my own smart_pointer, which counts the references to the thing it points to. Here is my implementation so far:
#pragma once
#include <iostream>
template <typename T>
class smart_pointer{
T* pointer;
int* cnt;
public:
smart_pointer<T>(T *el): pointer(el) { int i = 1; cnt = &i; }; //
smart_pointer<T>(const smart_pointer<T>& other): pointer(other.pointer) {
// std::cout << ", *(other.cnt): " << *(other.cnt);
cnt = other.cnt;
(*cnt)++;
} // Copy-constructor
int counter(){
int c = *cnt;
return c;
}
};
In main.cpp, I did the following:
int main(){
// smart_pointer_examples();
std::string h("hello");
smart_pointer<std::string> p(&h);
std::cout << "p: " << p.counter();
smart_pointer<std::string> q(p);
std::cout << ", q: " << q.counter() << std::endl;
return 0;
}
The problem is that that outputs p: 1, q: 6487781. After a lot of time trying to find the issue by debugging and printing stuff, I found something that fixed my issue: By adding std::cout << ", *(other.cnt): " << *(other.cnt); somewhere in my copy-constructor, the output becomes p: 1, *(other.cnt): 1, q: 2, which is the desired behaviour. I can't for the life of me think of why printing the counter would change anything.
Edit: Also, if I only do *(other.cnt) without std::cout, the same problem that I started with happens.
You made a small mistake in implementing your idea.
I will not comment on the design of your smart pointer implementation.
The problem is that you implemented your counter as a pointer. That is wrong.
And, you are dereferencing a local variable. That is a semantic bug. The result is undefined. The value of the counter will be indeterminate. Additionally you should initialize your class members.
If we fix both, then your code will look like:
#pragma once
#include <iostream>
template <typename T>
class smart_pointer {
T* pointer{};
int cnt{};
public:
smart_pointer<T>(T* el) : pointer(el) { cnt = 1; }; //
smart_pointer<T>(const smart_pointer<T>& other) : pointer(other.pointer) {
// std::cout << ", *(other.cnt): " << *(other.cnt);
cnt = other.cnt;
cnt++;
} // Copy-constructor
int counter() const {
return cnt;
}
};
int main() {
// smart_pointer_examples();
std::string h("hello");
smart_pointer<std::string> p(&h);
std::cout << "p: " << p.counter();
smart_pointer<std::string> q(p);
std::cout << ", q: " << q.counter() << std::endl;
return 0;
}
#include <iostream>
using namespace std;
template<class KeyT, class ValueT>
struct KeyValuePair {
const KeyT &key_;
const ValueT &value_;
KeyValuePair() {
cout << "KeyValuePair() constructor" << endl;
}
KeyValuePair( const KeyValuePair<KeyT, ValueT> &other) {
cout << "KeyvaluePiar copy constructor" << endl;
}
KeyValuePair(KeyT key, ValueT value) : key_(key), value_(value) {
cout << "KeyValuePair(KeyT, ValueT) constructor" << " key_: " << key_ << " value_ " << value_ << endl;
}
~KeyValuePair() {}
};
struct foo {
int i;
};
void dump(const KeyValuePair<int, foo*> &kp) {
//printf("dump printf key: %d, value: %p\n", kp.key_, kp.value_);
cout << "dump cout key_: " << kp.key_ << " value_: " << kp.value_ << " i: " << (kp.value_)->i << "\n";
}
int main() {
cout << "test kv\n";
foo *ptr = new foo();
ptr->i = 3000;
printf("address of ptr: %p\n", ptr);
dump(KeyValuePair<int, foo*>(10, ptr));
return 0;
}
Run it with
g++ -g -std=c++11 -fPIC -O0 -o main main.cc && ./main
on a Linux machine.
In the above c++ example code gives the following result
test kv
address of ptr: 0x18a1010
KeyValuePair(KeyT, ValueT) constructor key_: 10 value_ 0x18a1010
dump cout key_: 10 value_: 0x7fffae060070 i: -1375338428
It seems that KeyValuePair's value_ is messed up after calling dump function, anyone knows the reason? It seems to be related to reference and pointers.
Your member variable is a reference:
const KeyT &key_;
Your constructor, on the other hand, passes by value:
KeyValuePair(KeyT key, ValueT value)
That means you are storing a reference to a temporary variable that will get destroyed almost immediately.
One solution would be to pass by reference in your constructor:
KeyValuePair(KeyT& key, ValueT& value)
which is better, but not perfect, since you pass a int literal 10 into the function.
If you really just need a pair, the best solution is probably to use std::pair.
#include <iostream>
using namespace std;
class Machine
{
class State *current;
public:
Machine();
void setCurrent(State *s)
{
current = s;
}
void on();
void off();
};
class State
{
public:
virtual void on(Machine *m)
{
cout << " already ON\n";
}
virtual void off(Machine *m)
{
cout << " already OFF\n";
}
};
void Machine::on()
{
current->on(this);
}
void Machine::off()
{
current->off(this);
}
class ON: public State
{
public:
ON()
{
cout << " ON-ctor ";
};
~ON()
{
cout << " dtor-ON\n";
};
void off(Machine *m);
};
class OFF: public State
{
public:
OFF()
{
cout << " OFF-ctor ";
};
~OFF()
{
cout << " dtor-OFF\n";
};
void on(Machine *m)
{
cout << " going from OFF to ON";
m->setCurrent(new ON());
delete this;
}
};
void ON::off(Machine *m)
{
cout << " going from ON to OFF";
m->setCurrent(new OFF());
delete this;
}
Machine::Machine()
{
current = new OFF();
cout << '\n';
}
int main()
{
void(Machine:: *ptrs[])() =
{
Machine::off, Machine::on
};
Machine fsm;
int num;
while (1)
{
cout << "Enter 0/1: ";
cin >> num;
(fsm. *ptrs[num])();
}
}
There are a few bits of code I don't completely understand.
First, what does this do exactly?
(fsm. *ptrs[num])();
It looks like it's calling a default constructor of state, but I am not totally sure. Also, I don't understand where the on and off method is called. I think the object machine is the calling object for the on and off method, but I am not even sure.
Lastly, why do we destroy this?
void on(Machine *m)
{
cout << " going from OFF to ON";
m->setCurrent(new ON());
delete this;
}
Is it only for memory management?
I have rewritten the code with two function pointers and some comments:
Instead of array of function pointers, I have used 2 diff pointers and I am using if else for making the decision for switching state.
Main:
int main()
{
void (Machine::*offptr)() = &Machine::off; //offptr is a member funct pointer that now points to Machine::off function
void (Machine::*onptr)() = &Machine::on; //onptr is a member funct pointer that now points to Machine::on function
Machine fsm;
int num;
while (1)
{
cout<<"Enter 0/1: ";
cin>>num;
if( num == 0 )
{
(fsm.*offptr)(); //Here your are calling the function pointed to by the offptr (i.e., Machine::off) using the pointer
}
else if( num == 1 )
{
(fsm.*onptr)(); //Here your are calling the function pointed to by the onptr (i.e., Machine::on) using the pointer
}
}
}
In your example, all the decision is taken with the help of pointer array indices it self. So if user presses 0 the function pointed by ptrs[0] will be called and for 1 the function pointed by ptr[1] will be called. But since there is no check to make sure the user entered 0/1, the program will crash if the user enters something other than 0 or 1.
void on(Machine *m)
{
cout << " going from OFF to ON";
m->setCurrent(new ON()); //Here you are changing the state of the machine from OFF to ON (Note: call comes to this function only if the previous state was OFF).
delete this; //The previous state instance (OFF state pointed by this pointer) of the machine is no more required. So you are deleting it.
}
When i am passing an object to a function, I am getting undesired results. It seems to happen when I pass a Character through a Mage's action() function.
Here are some snippits of my code:
character.h
class Character {
public:
Character();
int getMaxLives() const;
int getMaxCraft() const;
protected:
maxLives;
maxCraft;
};
character.cpp
#include "character.h"
Character::Character () {
maxLives = 5;
MaxCraft = 10;
}
int Character::getMaxLives() const {
return maxLives;
}
int Character::getMaxCraft() const {
return maxCraft;
}
mage.h
#include "character.h"
class Mage {
public:
Mage();
void action(Character c1);
};
mage.cpp
#include "mage.h"
Mage::Mage () { ... }
void Mage::action(Character c1) {
cout << "Max Craft: " << c1.getMaxCraft() << endl;
cout << "Max Lives: " << c1.getMaxLives() << endl;
}
driver.cpp
int main () {
Character c1;
Mage m1;
m1.action(c1);
My ouput gives me the following:
Max Craft: 728798402 (The number varies)
Max Lives: 5
However, if in my diver, i do:
cout << "Max Craft: " << c1.getMaxCraft() << endl;
cout << "Max Lives: " << c1.getMaxLives() << endl;
I get:
Max Craft: 10
Max Lives: 5
Any ideas?
Looks like you meant for MaxCraft = 10; (in your default constructor) to actually be maxCraft = 10;. As #chris says in the comments, it appears that you're using some (evil, evil) C++ extension that allows implicitly-typed variables, so the MaxCraft = 10; line is simply defining a new variable named MaxCraft.
I'm trying to create a relatively type safe(but dynamic) and efficient concept called "Linkable Properties". A linkable property is similar to C#'s ability to bind properties and such and similar to the signal/slot model.
A linkable property is a type that can link itself to the values of other types. When any value changes all values are updated. This is useful when you need to keep several properties/values updated simultaneously. Once you setup a link everything is taken care of for you.
Can link from any type to any other type (in theory, this is the issue)
Links use a linked list rather than a list. This is more efficient both memory and speed and the real benefit of using this approach.
Converters are used to convert the values from one type to another(from 1, required, also an issue)
Can act like a getter and setter.
The issues I'm struggling with is writing the ability to link and convert to any type. The following code works with minor changes(convert the templated Chain function to a non-templated version and Change Chain<F> to Chain in the SetLink function). The problem is, the links are not correctly called.
This class almost works(it does compile and run but does not work as expected. Without the changes above the binding function never calls. It is only test code and not properly coded(please don't comment about using the static counter, it's just a temporary fix). The Chain and Link elements are the crucial aspect.
Chain is simply suppose to convert and update the value of the property then pass it along(or possibly the original value) to the next property. This continues until one reaches back to the original property in which case it will terminate.
#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace std;
static int iLCount = 1;
template <typename T>
class LinkableProperty
{
public:
std::string Name;
boost::function<void(T)> Link;
T Value;
template<typename F>
void Chain(F val)
{
Value = val;
std::cout << this->Name << " - " << this << ", " << &Link << ", " << val << " ! " << this->Value << " - " << "\n";
if (--iLCount < 0) return;
if (!Link.empty()) Link(Value);
}
LinkableProperty() { Link = NULL; Value = T(); Name = "Level " + std::to_string(iLCount++); };
void operator =(T value) { Value = value; }
template<typename F> void SetLink(LinkableProperty<F> &p)
{
Link = boost::bind(&LinkableProperty<F>::template Chain<F>, &p, _1);
}
void operator ()()
{
if (!Link.empty()) Link(Value);
}
};
int main()
{
LinkableProperty<unsigned short> L1;
LinkableProperty<double> L2;
L2.SetLink(L1);
L1.SetLink(L2);
L1 = 1;
L2 = 1.1;
L1();
cout << "----------\n" << L1.Value << ", " << L2.Value << endl;
getchar();
return 0;
}
The problem most likely stems from here:
template<typename F> void SetLink(LinkableProperty<F> p)
You are passing in a copy of the original property. Change this to accept a reference (or pointer), and you may have better luck. For example:
template<typename F>
void SetLink(LinkableProperty<F>* p)
{
Link = boost::bind(&LinkableProperty<F>::template Chain<F>, p, _1);
}
Should work as expected...
EDIT: Updated to show how to preserve the type across the conversion:
template <typename FT, typename TT>
TT convert(FT v)
{
return v; // default implicit conversion
}
template<>
double convert(unsigned short v)
{
std::cout << "us->d" << std::endl;
return static_cast<double>(v);
}
template<>
unsigned short convert(double v)
{
std::cout << "d->us" << std::endl;
return static_cast<unsigned short>(v);
}
static int iLCount = 1;
template <typename T>
class LinkableProperty
{
template <typename U>
struct _vref
{
typedef U vt;
_vref(vt& v) : _ref(v) {}
U& _ref;
};
public:
std::string Name;
boost::function<void(_vref<T>)> Link;
T Value;
template<typename F>
void Chain(F const& val)
{
Value = convert<typename F::vt, T>(val._ref);
std::cout << this->Name << " - " << this << ", " << &Link << ", " << val._ref << " ! " << this->Value << " - " << "\n";
if (--iLCount < 0) return;
if (!Link.empty()) Link(Value);
}
LinkableProperty() { Link = NULL; Value = T(); Name = "Level " + std::to_string(iLCount++); };
void operator =(T value) { Value = value; }
template<typename F>
void SetLink(LinkableProperty<F>* p)
{
Link = boost::bind(&LinkableProperty<F>::template Chain<_vref<T>>, p, _1);
}
void operator ()()
{
if (!Link.empty()) Link(_vref<T>(Value));
}
};
int main()
{
LinkableProperty<unsigned short> L1;
LinkableProperty<double> L2;
L2.SetLink(&L1);
L1.SetLink(&L2);
L1 = 1;
L2 = 1.1;
L1();
cout << "----------\n" << L1.Value << ", " << L2.Value << endl;
getchar();
return 0;
}
NOTE: There is some link bug which means that the updates trigger more times than necessary - you should check that...