My thread Stops - c++

My problem is that I am starting a Thread to read data from my EyeTracker. I start it using the following functions:
BlinkMode::BlinkMode()
{
bBlink = false;
threadStopped = true;
recordeddata = nullptr;
gT = GazeTracker::getGazeTracker();
canRecord = false;
numCameras = gT->getNumCameras();
if( numCameras >0){
canRecord = true;
}
filename = "blinkmode.txt";
counter = 0;
calipointno = 0 ;
}
void BlinkMode::startRecording()
{
if (!bBlink)
{
// Turn thread loop signal on
bBlink = true;
bBlinkSuccess = false;
bExcessData = false;
blinkThread = std::thread(createBlinkThread, this);
}
}
void BlinkMode::createBlinkThread(void* instance)
{
BlinkMode* pThis = (BlinkMode*) instance;
pThis->bBlink;
if(pThis->canRecord){
pThis->threadStopped = false;
pThis->BlinkModeThread();
pThis->threadStopped = true;
}
}
void BlinkMode::BlinkModeThread ()
{
BlinkMode* pThis = (BlinkMode*) this;
pThis->bBlink;
Matrix mProvData = Matrix (DR_DATAANALYSIS, GT_EYEDATALENGTH);
Matrix aSourceMatrix = Matrix (DR_MAXRECORDEDDATA, GT_EYEDATALENGTH);
recordeddata = new float[DR_MAXRECORDEDDATA][GT_EYEDATALENGTH];
while(bBlink){
if(counter<DR_MAXRECORDEDDATA){
gT->getCurrentData(recordeddata[counter],ALLDATA);
[ETC ...]
The thing is that my boolean bBlink, which is defined as a private volatile boolean in the header file of my class:
class BlinkMode
{
private:
// Monitor thread control signal.
volatile bool bBlink;}
becomes false right after the creation of the Matrix instances, (Matrix is another class of my code). And hence, the while loop is NEVER entered. However, if I comment the Matrix lines, it works! I can even execute the new float "recordeddata", but not the Matrices.
Does that mean that I cannot call another classes while I am inside a Thread or something? Sorry I am pretty new with C++ and I am lost.
Any help please??
Thanks in advance!

The Matrix class is just to initialize Matrices in different ways and do operations with them, kind of like this:
class Matrix
{
public:
// Default constructor
Matrix();
// Default destructor
~Matrix();
// Initialise matrix of rows x cols.
Matrix(const int rows, const int cols);
// Convert a two dimensional array (rows x cols) of integers to a matrix.
Matrix(const int* const* num, const int rows, const int cols);
// Convert a two dimensional array (rows x cols) of floats to a matrix.
Matrix(const float* const* num, const int rows, const int cols);
// Copies the required row into the array.
void getRow(const int row, double[]) const;
// Copies the required row into the matrix.
void getRow(const int row, Matrix&) const;
// Sets the values of a row to the values of the array.
void setRow(const int row, const int[]);
enter code here
So I am just creating 2 objects there, and that is when the boolean automatically changes to false!!
I just created the pThis pointer you mentioned to be able to access the value of the boolean and check when it changes, but it is not relevant for the code... I can erase it and nothing changes...

Related

Use only one column of array as function argument

Suppose I have a very large array of data:
double matrix[100000][100] = {0.0};
During runtime this data is updated. Now I want to give the reference to this data to a function FUNC. However, I want to only give one column to the function FUNC, like:
FUNC(matrix["all elements"]["only column with index 5"]);
and not the entire array. Furthermore, I dont want to perform a copy operation before (because this is slow), I just want to give the pointer or reference to the specific rows/columns inside the large array data. The function should only see an array like:
void FUNC(double* array)
{
for (int i = 0; i < 100000; i++)
doSomething(array[i]);
}
How do I do give this partial data from array "matrix" to the function FUNC?
The column values of your matrix are not sequential in memory, so you can't pass a single column to FUNC() without making a copy of the data into a sequential array. However, if you are able to add the column index as an additional parameter to FUNC() then you can do something like this instead:
const int MAX_ROWS = ...;
const int MAX_COLS = ...;
using Matrix = double[MAX_ROWS][MAX_COLS];
void doSomething(double value)
{
...
}
void FUNC(const Matrix& matrix, int column)
{
for (int row = 0; row < MAX_ROWS; ++row) {
doSomething(matrix[row][column]);
}
}
Matrix matrix = {};
...
FUNC(matrix, 5);
Online Demo

Sorting a vector of custom class doesn't iterate over the vector correctly

I am trying to implement a painters sort algorithm for a rendering assignment. The premise of the code is that I need to find the average depth of a polygon, and the list of polygons via the depth assigned to them by the for loop.
this is the polygons declaration, as well as a collection of the vertices of the polygon post transformation which are used for the calculation of the depth of the polygon
std::vector<Polygon3D> _polygons;
std::vector<Vertex> _transvertices;
This is the method called by the model class to sort the _polygons vector using std::sort
void Model::Sort()
{
for (int i = 0; i <= GetPolygonCount(); i++)
{
_polygons[i].SetDepth((_transvertices[_polygons[i].GetIndex(0)].Get(2) + _transvertices[_polygons[i].GetIndex(1)].Get(2) + _transvertices[_polygons[i].GetIndex(2)].Get(2)) / 3);
}
sort(_polygons.begin(), _polygons.end(), sortByDepth);
}
This code then links to this binary predicate
bool sortByDepth(const Polygon3D &lhs, const Polygon3D &rhs)
{
float m = lhs.GetDepth(); //For value testing
float n = rhs.GetDepth(); //For value testing
return lhs.GetDepth() > rhs.GetDepth();
}
The issue is, once the sort algorithm starts, the value of lhs and rhs never change - lhs always has a depth of 0 (and looking further into its assignment, it seems to be creating an entirely new polygon?) and rhs always has a value of 30.53 (the depth of the first polygon in the _polygons vertex
I'm concerned that the issue might be with not having a form of iterator linked to the Polygon3D class, but I wouldn't know where to start with making an iterator for the class.
Any help would be appreciated, I've looked through far too many similar questions, but none of them seem to be quite right for my particular problem.
EDIT:
Post got taken down because I didn't provide enough code apparently. I tried to reproduce the problem in a different project but for some reason it iterates just fine there.
This is the "shortest possible reproduction" I tried, but for some reason this doesn't seem to have the same issue as the original.
#include <vector>
#include <algorithm>
class Polygon3D
{
public:
Polygon3D(); // Example data for testing purposes
float GetDepth() const;
void SetDepth(float depth);
private:
float _depthAverage;
};
class Model
{
public:
Model();
size_t GetPolygonCount() const;
void Sort();
private:
std::vector<Polygon3D> _polygons;
std::vector<int> _vertices;
std::vector<int> _transvertices;
};
Polygon3D::Polygon3D()
{
//_depthAverage = float(rand() % 100);
}
float Polygon3D::GetDepth() const
{
return _depthAverage;
}
void Polygon3D::SetDepth(float depth)
{
_depthAverage = depth;
}
Model::Model()
{
for (int i = 0; i < 10; i++)
{
_polygons.push_back(Polygon3D());
}
this->Sort();
}
size_t Model::GetPolygonCount() const
{
return _polygons.size() - 1;
}
bool sortByDepth(const Polygon3D& lhs, const Polygon3D& rhs)
{
float m = lhs.GetDepth();
float n = rhs.GetDepth();
return lhs.GetDepth() > rhs.GetDepth();
}
void Model::Sort()
{
for (int i = 0; i <= GetPolygonCount(); i++)
{
_polygons[i].SetDepth(float(rand() % 100) / 3);
}
sort(_polygons.begin(), _polygons.end(), sortByDepth);
}
int main()
{
Model m = Model();
}
Edit 2:
I played around with just using an auto type variable to manually iterate over _polygons, and that seems to work. I dont understand why std::sort doesnt
auto begin = _polygons.begin();
while(true)
{
begin++;
}
The answer turned out to be something incredibly stupid on my own part. The issue was the copy constructor used within the Polygon3D class - I had forgotten to copy over the depth value in the copy constructor, which meant lhs did not get a depth value.

C++ Avoiding Triple Pointers

I am trying to create an array of X pointers referencing matrices of dimensions Y by 16. Is there any way to accomplish this in C++ without the use of triple pointers?
Edit: Adding some context for the problem.
There are a number of geometries on the screen, each with a transform that has been flattened to a 1x16 array. Each snapshot represents the transforms for each of number of components. So the matrix dimensions are 16 by num_components by num_snapshots , where the latter two dimensions are known at run-time. In the end, we have many geometries with motion applied.
I'm creating a function that takes a triple pointer argument, though I cannot use triple pointers in my situation. What other ways can I pass this data (possibly via multiple arguments)? Worst case, I thought about flattening this entire 3D matrix to an array, though it seems like a sloppy thing to do. Any better suggestions?
What I have now:
function(..., double ***snapshot_transforms, ...)
What I want to accomplish:
function (..., <1+ non-triple pointer parameters>, ...)
Below isn't the function I'm creating that takes the triple pointer, but shows what the data is all about.
static double ***snapshot_transforms_function (int num_snapshots, int num_geometries)
{
double component_transform[16];
double ***snapshot_transforms = new double**[num_snapshots];
for (int i = 0; i < num_snapshots; i++)
{
snapshot_transforms[i] = new double*[num_geometries];
for (int j = 0; j < num_geometries; j++)
{
snapshot_transforms[i][j] = new double[16];
// 4x4 transform put into a 1x16 array with dummy values for each component for each snapshot
for (int k = 0; k < 16; k++)
snapshot_transforms[i][j][k] = k;
}
}
return snapshot_transforms;
}
Edit2: I cannot create new classes, nor use C++ features like std, as the exposed function prototype in the header file is getting put into a wrapper (that doesn't know how to interpret triple pointers) for translation to other languages.
Edit3: After everyone's input in the comments, I think going with a flattened array is probably the best solution. I was hoping there would be some way to split this triple pointer and organize this complex data across multiple data pieces neatly using simple data types including single pointers. Though I don't think there is a pretty way of doing this given my caveats here. I appreciate everyone's help =)
It is easier, better, and less error prone to use an std::vector. You are using C++ and not C after all. I replaced all of the C-style array pointers with vectors. The typedef doublecube makes it so that you don't have to type vector<vector<vector<double>>> over and over again. Other than that the code basically stays the same as what you had.
If you don't actually need dummy values I would remove that innermost k loop completely. reserve will reserve the memory space that you need for the real data.
#include <vector>
using std::vector; // so we can just call it "vector"
typedef vector<vector<vector<double>>> doublecube;
static doublecube snapshot_transforms_function (int num_snapshots, int num_geometries)
{
// I deleted component_transform. It was never used
doublecube snapshot_transforms;
snapshot_transforms.reserve(num_snapshots);
for (int i = 0; i < num_snapshots; i++)
{
snapshot_transforms.at(i).reserve(num_geometries);
for (int j = 0; j < num_geometries; j++)
{
snapshot_transforms.at(i).at(j).reserve(16);
// 4x4 transform put into a 1x16 array with dummy values for each component for each snapshot
for (int k = 0; k < 16; k++)
snapshot_transforms.at(i).at(j).at(k) = k;
}
}
return snapshot_transforms;
}
Adding a little bit of object-orientation usually makes the code easier to manage -- for example, here's some code that creates an array of 100 Matrix objects with varying numbers of rows per Matrix. (You could vary the number of columns in each Matrix too if you wanted to, but I left them at 16):
#include <vector>
#include <memory> // for shared_ptr (not strictly necessary, but used in main() to avoid unnecessarily copying of Matrix objects)
/** Represents a (numRows x numCols) 2D matrix of doubles */
class Matrix
{
public:
// constructor
Matrix(int numRows = 0, int numCols = 0)
: _numRows(numRows)
, _numCols(numCols)
{
_values.resize(_numRows*_numCols);
std::fill(_values.begin(), _values.end(), 0.0f);
}
// copy constructor
Matrix(const Matrix & rhs)
: _numRows(rhs._numRows)
, _numCols(rhs._numCols)
{
_values.resize(_numRows*_numCols);
std::fill(_values.begin(), _values.end(), 0.0f);
}
/** Returns the value at (row/col) */
double get(int row, int col) const {return _values[(row*_numCols)+col];}
/** Sets the value at (row/col) to the specified value */
double set(int row, int col, double val) {return _values[(row*_numCols)+col] = val;}
/** Assignment operator */
Matrix & operator = (const Matrix & rhs)
{
_numRows = rhs._numRows;
_numCols = rhs._numCols;
_values = rhs._values;
return *this;
}
private:
int _numRows;
int _numCols;
std::vector<double> _values;
};
int main(int, char **)
{
const int numCols = 16;
std::vector< std::shared_ptr<Matrix> > matrixList;
for (int i=0; i<100; i++) matrixList.push_back(std::make_shared<Matrix>(i, numCols));
return 0;
}

A vector of unique_ptr at specific positions in vector

I have a class called Grid which is composed of Cells. Each cell can have its own format (the concept is similar to MS Excel).
The format in the Grid is kept in a vector std::vector<std::unique_ptr<CellFormat>> m_CellFormatTable which owns all the formatting, so whenever I need to read a Cells format, I read it from the vector and whenever there is a change, it is reported back to the vector. Sorry, I am quite new to C++11 standards so my thinking might be wrong.
Since a grid is a matrix and each cell belongs to a different part of the matrix when there is a change in a cell's format it should be reflected in the correct part of the matrix, namely positioned correctly in the vector (CellFormatTable). Therefore, at this stage I cannot use the push_back method of the vector.
The CellFormat class:
struct CellFormat
{
wxFont m_Font;
wxColor m_BackgroundColor, m_TextColor;
int m_HorizontalAlignment, m_VerticalAlignment;
CellFormat(Grid* ws) {
m_BackgroundColor = ws->GetDefaultCellBackgroundColour();
m_TextColor=ws->GetDefaultCellTextColour();
int horizontal = 0, vertical = 0;
ws->GetDefaultCellAlignment(&horizontal, &vertical);
}
CellFormat(const CellFormat& other) {
m_Font = other.m_Font;
m_BackgroundColor = other.m_BackgroundColor;
m_TextColor = other.m_TextColor;
m_HorizontalAlignment = other.m_HorizontalAlignment;
m_VerticalAlignment = other.m_VerticalAlignment;
}
CellFormat& operator=(const CellFormat& other) {
if (this == &other) return *this;
m_Font = other.m_Font;
m_BackgroundColor = other.m_BackgroundColor;
m_TextColor = other.m_TextColor;
m_HorizontalAlignment = other.m_HorizontalAlignment;
m_VerticalAlignment = other.m_VerticalAlignment;
return *this;
}
};
In the Grid.h
class Grid{
std::vector<std::unique_ptr<CellFormat>> m_CellFormatTable;
//
CellFormat* GetCellFormat(int row, int column);
void SetCellFormat(int row, int column, CellFormat format);
void ApplyCellFormat(int row, int column, const CellFormat* format);
CellFormat* CreateCellFormat(int row, int column);
//rest is omitted
}
In Grid.cpp
Grid(some arguments){
m_CellFormatTable.resize(nrows*ncols);
//rest is omitted
}
CellFormat* Grid::GetCellFormat(int row, int column)
{
int ncols= GetNumberCols();
return m_CellFormatTable[row*ncols+ column].get();
}
void Grid::SetCellFormat(int row, int column, CellFormat other)
{
CellFormat* format = GetCellFormat(row, column);
if (format == 0) format = CreateCellFormat(row, column);
*format = other;
}
void Grid::ApplyCellFormat(int row, int column, const CellFormat * format)
{
if (format == 0) {
int ncols= GetNumberCols();
//Set everything to default values
//Omitted
m_CellFormatTable[row*ncols+ column].reset();
}
else {
wxColor bgcolor = format->m_BackgroundColor;
if (bgcolor.IsOk()) SetCellBackgroundColour(row, column, bgcolor);
SetCellTextColour(row, column, format->m_TextColor);
SetCellFont(row, column, format->m_Font);
SetCellAlignment(row, column, format->m_HorizontalAlignment, format->m_VerticalAlignment);
}
}
CellFormat* Grid::CreateCellFormat(int row, int column)
{
int ncols= GetNumberCols();
CellFormat* format = new CellFormat(this);
m_CellFormatTable.emplace(m_CellFormatTable.begin() + row*ncols+ column, std::move(format));
return format;
}
Whenever I format a cell, say its background color is changed, I use the following attempt:
CellFormat* format = ws->GetCellFormat(row, col);
if (format == 0) format = ws->CreateCellFormat(row, col);
if (ChangeFillColor) {
ws->SetCellBackgroundColour(row, col, m_LastChosenFillColor);
format->m_BackgroundColor = m_LastChosenFillColor;
}
The code fails at ApplyCellFormat function at the point of format->m_BackgroundColor since the color which should have been Cell's background color is not valid. This tells me that most and highly likely CreateCellFormat does not place CellFormat in the right location. I try to use insert rather than emplace but compiler (VS 2015) complained all my attempts.
Any ideas appreciated.
You have several problems.
One is that you add a CellFormat* but your vector stores unique_ptr ;so you need std::make_uniquewith the new format.
Question: are you sure you need a vector of pointers instead of objects?
Other is that you presume the vector to have all data for all cells, being 0 if they are not set yet. That's wrong. The vector only have as many elements as you have 'pushed' or 'emplaced'.
Let's say you have 'pushed' the format for cell (0,0). Now you want to set the format for (5,2) which is (say you have 10 cols) the 52th element in the vector, but you have only one. So vector[51] is undefined (vector.at(51) will raise an error).
Add all cell formats first, with some value = 0 to tell it has not been set yet. Or re-think your strategy.
By the way, you can use wxGridCellAttr which provides what you are coding on your own.
From the fact that you use a vector of unique_ptr (rather than of objects), I deduce that not all elements of the matrix are actually occupied. In this case, it may be better to use a std::map (or std::unordered_map if the matrix is very large) of objects (not unique_ptrs).
template<typename T>
struct grid
{
using index = std::pair<unsigned, unsigned>;
// insert element if not already present
// returns if insertion occurred
template<typename...Args>
bool insert(index const&i, Args&&...args)
{
return data.emplace(std::forward<Args>(args)...).second;
}
// remove element (if it exists)
void remove(index const&i)
{
data.erase(i);
}
// get pointer to element, may be nullptr
T* get(index const&i)
{
auto it = data.find(i);
return it==data.end() ?
nullptr : std::addressof(*it);
}
private:
std::map<index,T> data;
};
The reason I see that your code is failing in this section of your code:
CellFormat* format = ws->GetCellFormat(row, col);
if (format == 0) format = ws->CreateCellFormat(row, col);
if (ChangeFillColor) {
ws->SetCellBackgroundColour(row, col, m_LastChosenFillColor);
format->m_BackgroundColor = m_LastChosenFillColor;
}
Is due to how your class is defined:
class Grid{
std::vector<std::unique_ptr<CellFormat>> m_CellFormatTable;
//
CellFormat* GetCellFormat(int row, int column);
void SetCellFormat(int row, int column, CellFormat format);
void ApplyCellFormat(int row, int column, const CellFormat* format);
CellFormat* CreateCellFormat(int row, int column);
//rest is omitted
}
By Default your class has it's members and functions set as private:
Change your class to this:
class Grid {
public:
typedef std::vector<std::unique_ptr<CellFormat>> Format;
private:
Format m_CellFormatTable;
public:
CellFormat* getCellFormat( int row, int column );
void setCellFormat( int row, int column, const CellFormat& format );
void applyCellFormat( int row, int column, const CellFormat& format );
// Add This Function If Needed
Format getCellFormatTable() const { return m_CellFormatTable; }
};
So your class's member functions are declared as public: Then outside and non-friend objects can now have access to this class's member functions and be able to return the data structure via a get method.
Thanks to all for helpful comments and posts. Finally it works as expected.
As Ripi2 suggested, CellFormat objects in the vector were not initialized, so in the constructor I initialized them. Also not presented here, I had somewhere in the code a vector of objects not initialized, so corrected that part as well.
Although looping through all the rows and columns of the grid and creating a default format is NOT the best idea, a future work for me will be Walter's suggestion, i.e. to use sets.
Grid(some arguments){
for (int i = 0; i < nrows*ncols; i++) {
m_CellFormatTable.emplace_back(new CellFormat(this));
}
//Rest is omitted
}
Also corrected below code as well:
CellFormat* Grid::CreateCellFormat(int row, int column)
{
int ncols = GetNumberCols();
CellFormat* format = new CellFormat(this);
std::unique_ptr<CellFormat> ptr(format);
m_CellFormatTable.emplace(m_CellFormatTable.begin() + row*ncols + column,std::move(ptr));
return format;
}
One way to keep track of formatting is:
CellFormat* format = ws->GetCellFormat(i, j);
if (ChangeFillColor) {
ws->SetCellBackgroundColour(i, j, m_LastChosenFillColor);
format->m_BackgroundColor = m_LastChosenFillColor;
}

Return cv::Mat* variable does not work as expected

When returning a OpenCV cv::Mat* variable (correctly initialized) it seems like it looses all of its content. What am I doing wrong?
// #called function
template<mxClassID CID>
cv::Mat* helper_2dmat_to_mat_ptr(const mxArray* mat) {
int M = mxGetM(mat), N = mxGetN(mat);
const int TYPE = mcv_traits<CID>::CV_TYPE;
cv::Mat pOutMat;
pOutMat.create(M, N, TYPE);
cv::Mat* pOutMat_ptr = &pOutMat;
void* pBegOut = static_cast<void*>(pOutMat_ptr->data);
int pitch = pOutMat_ptr->step;
typedef typename mc_traits<CID>::CT T;
void* pBeg = mxGetData(mat);
pix_iterator_2d<T, eColWise> it_src1(
static_cast<T*>(pBeg), N, M);
pix_iterator_2d<T, eColWise> it_src2(
static_cast<T*>(pBeg), N, M);
it_src2.end();
pix_iterator_2d<T, eRowWise> it_dest(
static_cast<T*>(pBegOut), N, M, pitch);
std::copy(it_src1, it_src2, it_dest);
/**
* If I check the content of 'pOutMat' here, it correctly
* contains the matrix it is supposed to contain (i.e. a [3x3] matrix
* with numbers from 1 to 9)
*/
return pOutMat_ptr;
}
// #caller function
cv::Mat* mxArr_to_new_Mat_ptr(const mxArray* mat) {
const mxClassID id = mxGetClassID(mat);
mwSize const ndim = mxGetNumberOfDimensions(mat);
if (2 == ndim) {
if (mxDOUBLE_CLASS == id) {
cv:: Mat* out = helper_2dmat_to_mat_ptr<mxDOUBLE_CLASS>(mat);
/**
* If I check the content of 'out' here it seems empty
*/
}
else if (...)
}
... other irrelevant code ...
}
My question is simple: why before the 'return' command the pointer points to a non-empty matrix whereas when the control goes back to the caller function this data seems disapperared?
My guess would be that it has to do with the fact that the inner function (helper_2dmat_to_mat_ptr) has a scope which cannot be seen from the outer function (mxArr_to_new_Mat_ptr), but how can I solve the problem? What is more, as you can see, the outer function (mxArr_to_new_Mat_ptr) is supposed to do some operation on the cv::Mat* before doing basically the same thing as the inner function.