when launching boost::thread the .exe chrashes - boost-bind

This is my function:
void cmdChangeSett(cmdbuf* cmd_buffer, CTimeTag tagger, uint8_t chNum, int mask) {
double* oldChannelvoltage = new double[chNum];
double* newChannelvoltage = new double[chNum];
bool* oldEdge = new bool[chNum];
bool* newEdge = new bool[chNum];
int newmask;
double chDiff;
int edgeDiff;
int i;
while (runAcquisition) {
for (i = 0; i < chNum; i++) {
cmd_getThresh_getEdge(cmd_buffer, i, oldChannelvoltage, oldEdge);
}
Sleep(500);
newmask = 0;
for (i = 0; i < chNum; i++) {
cmd_getThresh_getEdge(cmd_buffer, i, newChannelvoltage, newEdge);
chDiff = oldChannelvoltage[i] - newChannelvoltage[i];
edgeDiff = oldEdge[i] - newEdge[i];
//printf("\nOld: %.2f, New: %.2f -> DIFF = %.2f", oldChannelvoltage[i], newChannelvoltage[i], diff);
if (chDiff != 0) {
WARN(newChannelvoltage[i] > 1.5, newChannelvoltage[i] = 1.5f, "Threshold of %.2fV exceeds channel %i's max. Rounding to %.2fV.", newChannelvoltage[i], i + 1, 1.5);
WARN(newChannelvoltage[i] < -1.5, newChannelvoltage[i] = -1.5f, "Threshold of %.2fV exceeds channel %i's max. Rounding to %.2fV.", newChannelvoltage[i], i + 1, -1.5);
tagger.SetInputThreshold(i + 1, newChannelvoltage[i]);
}
if (edgeDiff) {
if (!newEdge[i]) newmask += 1 << i;
}
}
if (newmask != mask) {
tagger.SetInversionMask(newmask);
mask = newmask;
}
}
delete[] oldChannelvoltage;
delete[] newChannelvoltage;
delete[] oldEdge;
delete[] newEdge;
}
When I launch the thread from the main() it crashes:
int main(int argc, char** argv) {
int mask = 0;
cmdbuf* cmd_buffer;
CTimeTag tagger;
//some code ....
//......
boost::function<void()> cmdChangeSettThread = boost::bind(&cmdChangeSett,cmd_buffer, tagger, 16, mask);
boost::thread th(cmdChangeSettThread);
//some other code ...
return 0;
}
Any idea ??
I thought the problem was caused by the arrays I'm using in the function but I can't figure out how to solve the problem.
Thank you very much!

You need to wait for the thread to finish in main.
If the thread destructor is called and the thread is still running terminate() is called.
th.join(); // should stop the application crashing.
return 0;
}
PS. None of this is good:
double* oldChannelvoltage = new double[chNum];
double* newChannelvoltage = new double[chNum];
bool* oldEdge = new bool[chNum];
bool* newEdge = new bool[chNum];
Use a vector (or an array).
Get a code review: http://codereview.stackexchange.com

Thank you everybody! I found the problem!! I was stupidly passing the object CTimeTag tagger by value, I'm sorry if I wasn't super clear in presenting the problem!
So now the function definition is:
void cmdChangeSett(cmdbuf* cmd_buffer, CTimeTag *tagger, tt_buf* buffer, uint8_t chNum, int mask)
and when I'm calling it with boost::bind I have:
boost::function<void()> cmdChangeSettThread = boost::bind(&cmdChangeSett,cmd_buffer, &tagger, buffer, 16, mask);
Thank you again!

Related

Implementation of Dijkstra’s mutual exclusion algorithm

I am trying to implement a Dijkstra's algorithm into a fork/join threadpool (consists the main threadpool with a global task queue and N threads with its own task queue) based on Dijkstra's Solution of a problem in concurrent programming control and Frigo's and Leiserson's and Randall's The implementation of the cilk-5 multithreaded language.
But, it seems too complicated. So, I used Filter Lock from Art of Multiprocessor Programming as following:
Book's implementation
class Filter implements Lock {
int[] level;
int[] victim;
public Filter(int n) {
level = new int[n];
victim = new int[n]; // use 1..n-1
for (int i = 0; i < n; i++) {
level[i] = 0;
}
}
public void lock() {
int me = ThreadID.get();
for (int i = 1; i < n; i++) { //attempt level 1
level[me] = i;
victim[i] = me;
// spin while conflicts exist
while ((∃k != me) (level[k] >= i && victim[i] == me)) {};
}
}
public void unlock() {
int me = ThreadID.get();
level[me] = 0;
}
}
My implementation in threadpool
static int* flag;
static int* victim;
const int MAX = 1e9;
int ans = 0;
int nthreads = 10;
struct pt
{
int id;
pthread_t thread;
};
static bool existK(int j, int i, int nthreads){
for (int k = 0; k < nthreads ; k++){
if (flag[k] >= j && k != i)
{
return true;
}
}
return false;
}
void lock_init(void)
{
flag = (int *) calloc(nthreads, sizeof(int));
victim = (int *) calloc(nthreads, sizeof(int));
}
// Executed before entering critical section
void lock(int i)
{
for (int j = 1; j < nthreads; j++){
flag[i] = j;
victim[j] = i;
while (existK(j, i, nthreads) && victim[j] == i);
}
}
// Executed after leaving critical section
void unlock(int i)
{
flag[i] = 0;
}
// in main()
void* func(void *pw)
{
while (true) {
lock(threadID);
// working on its own queue if there is a task and
// after it finishes this task, call unlock(threadID) and call continue;
//if the global queue has tasks left, work on it and call unlock and continue
//if the other worker queue has tasks left, work on it and call unlock and continue
}
}
// Driver code
int main()
{
struct pt** ptr;
lock_init();
ptr = ((struct pt **)malloc(sizeof(struct pt *) * nthreads));
for (int i = 0; i < nthreads; i++){
ptr[i] = malloc(sizeof(struct pt));
(ptr[i])->id = i;
pthread_create(&(ptr[i])->thread, NULL, func, ptr[i]);
}
for (int i = 0; i < nthreads; i++){
pthread_join((ptr[i])->thread, NULL);
}
return 0;
}
However, with my implementation, the main loop is much slower than just using the pthread_mutex_lock and pthread_mutex_unlock. I am not sure if I use the algorithm in a wrong place or my algorithm is wrong at this point.
Additionally, I am wondering how to stealing tasks to work on from the
other workers’ queues in an efficient way (locating the worker with available tasks)

How to define copy constructor and deallocate pointer

I ran cppcheck, and it turns out that I need to have a copy constructor for this class. I do not know how to define a copy constructor in this case. Any suggestions?
class Simulator{
private:
int xMax;// = 40; //SIZE;
int yMax;// = 40; //xMax; // 40
//int TTMxSize = 4000;
//const int CarMxSize = 500;
//const int WaitListSize = 4000;
double base_price;// = 0.85 / 4;
double saev_vott;// = 0.35;
char* mode_output;// = "modeChoiceStats_supply_charge.csv";
vector<Car>** CarMx;//[xMax][yMax];
vector <Station>** ChStMx;//[xMax][yMax];
vector<int> **cellChargeCount;
vector<int> **cellChargeTime;
int timeTripCounts [288];
// Functions for program
public:
Simulator();
Simulator(int fleet_size, int seed, char* inputFile);
~Simulator();
bool loadParameters(char* input);
void printParameters();
void placeInitCars();
bool lookForCar (int x, int y, int r, int dist, int& cn);
void assignCar (int x, int y, int c, Trip* trp);
void setBusinessTripProbability();
void runSimulation();
};
Simulator::~Simulator()
{
for (int x=0; x<xMax; x++)
{
delete [] CarMx[x];
delete [] ChStMx[x];
delete [] cellChargeCount[x];
delete [] cellChargeTime[x];
}
for (int x=0; x<numZonesL; x++)
delete [] zoneSharesL[x];
for (int x=0; x<numZonesS; x++)
delete [] zoneSharesS[x];
delete [] CarMx;
delete [] ChStMx;
delete [] cellChargeCount;
delete [] cellChargeTime;
delete [] zoneSharesL;
delete [] zoneSharesS;
}
Also, I am getting Resource Leak error in the following function
bool Simulator::loadParameters(char* input)
{
FILE* inputfile;
inputfile = fopen(input, "r");
if (inputfile == NULL){
cout << "Could not open "<<input<<endl;
return false;
}
double inputVal = -1.0;
char* varStr;
char* valStr;
char instring [80];
while (!feof(inputfile))
{
fgets(instring, 80, inputfile);
comment = instring[0];
if (comment != '#' && comment != '\n')
{
varStr = strtok(instring, "=");
valStr = strtok(NULL, "\0");
if (strcmp (varStr, "xMax") == 0) {
inputVal = strtod(valStr, NULL);
xMax = 4 * (int) inputVal;
} else if (strcmp (varStr, "yMax") == 0) {
inputVal = strtod(valStr, NULL);
yMax = 4 * (int) inputVal;
}
}
return true; <<<<<<<<< RESOURCE LEAK: inputfile
}
Possible leak in this function: Pointer is not deallocated before being allocated.
void Simulator::setBusinessTripProbability()
{
businessTripProbability = new double[926];
businessTripProbability [ 0 ] = 0.0000 ;
businessTripProbability [ 1 ] = 0.0029 ;
businessTripProbability [ 2 ] = 0.0059 ;........... until [925]
I am a Cppcheck developer.
To create a copy constructor:
Simulator(const Simulator &sim);
If you do not plan to use the copy constructor, it's better to delete it:
Simulator(const Simulator &) = delete;
Resource leak: You need to use fclose(inputfile)
Possible leak: Imagine this code:
Simulator simulator;
simulator.setBusinessTripPossibility();
simulator.setBusinessTripPossibility();
There is a memory leak here. The businessTripProbability is allocated twice and there is no deallocation. You might have a rule that the public method setBusinessTripPossibility() will never be called twice. But in my humble opinion you should not design classes with such rule. Try to allow arbitrary use of the public class interface.

(opencv) merge contours together

I am doing a real time motion detection program. I find that there are a lot of contour made in my different image after i used background subtraction method . i would like to ask is there any method that can merge these contour together or make a larger rect contain all the contours?
the case now i have been done
http://singhgaganpreet.files.wordpress.com/2012/07/motioncolour.jpg
My code is here
#include <iostream>
#include <OpenCV/cv.h>
#include <OPenCV/highgui.h>
using namespace cv;
using namespace std;
CvRect rect;
CvSeq* contours = 0;
CvMemStorage* storage = NULL;
CvCapture *cam;
IplImage *currentFrame, *currentFrame_grey, *differenceImg, *oldFrame_grey;
bool first = true;
int main(int argc, char* argv[])
{
//Create a new movie capture object.
cam = cvCaptureFromCAM(0);
//create storage for contours
storage = cvCreateMemStorage(0);
//capture current frame from webcam
currentFrame = cvQueryFrame(cam);
//Size of the image.
CvSize imgSize;
imgSize.width = currentFrame->width;
imgSize.height = currentFrame->height;
//Images to use in the program.
currentFrame_grey = cvCreateImage( imgSize, IPL_DEPTH_8U, 1);
while(1)
{
currentFrame = cvQueryFrame( cam );
if( !currentFrame ) break;
//Convert the image to grayscale.
cvCvtColor(currentFrame,currentFrame_grey,CV_RGB2GRAY);
if(first) //Capturing Background for the first time
{
differenceImg = cvCloneImage(currentFrame_grey);
oldFrame_grey = cvCloneImage(currentFrame_grey);
cvConvertScale(currentFrame_grey, oldFrame_grey, 1.0, 0.0);
first = false;
continue;
}
//Minus the current frame from the moving average.
cvAbsDiff(oldFrame_grey,currentFrame_grey,differenceImg);
//bluring the differnece image
cvSmooth(differenceImg, differenceImg, CV_BLUR);
//apply threshold to discard small unwanted movements
cvThreshold(differenceImg, differenceImg, 25, 255, CV_THRESH_BINARY);
//find contours
cvFindContours( differenceImg, storage, &contours );
//draw bounding box around each contour
for(; contours!=0; contours = contours->h_next)
{
rect = cvBoundingRect(contours, 0); //extract bounding box for current contour
//drawing rectangle
cvRectangle(currentFrame,
cvPoint(rect.x, rect.y),
cvPoint(rect.x+rect.width, rect.y+rect.height),
cvScalar(0, 0, 255, 0),
2, 8, 0);
}
//display colour image with bounding box
cvShowImage("Output Image", currentFrame);
//display threshold image
cvShowImage("Difference image", differenceImg);
//New Background
cvConvertScale(currentFrame_grey, oldFrame_grey, 1.0, 0.0);
//clear memory and contours
cvClearMemStorage( storage );
contours = 0;
//press Esc to exit
char c = cvWaitKey(33);
if( c == 27 ) break;
}
// Destroy the image & movies objects
cvReleaseImage(&oldFrame_grey);
cvReleaseImage(&differenceImg);
cvReleaseImage(&currentFrame);
cvReleaseImage(&currentFrame_grey);
//cvReleaseCapture(&cam);
return 0;
}
Did you try this?
std::vector<cv::Point> points;
points.insert(points.end(), contour1.begin(), contour1.end());
points.insert(points.end(), contour2.begin(), contour2.end());
convexHull(cv::Mat(points), contour);
PS. For some applications, it may be better to use approxPoly() rather than convexHull(). Just try both.
PPS. Try smoothing the resulting contour with gaussian. It also can be helpful.
I came across a similar problem. In my case I created an empty sequence then I filled it with the points of each contour, after that I fitted a bounding ellipse with that sequence.
Here is my code segment...
CvMemStorage *storage = cvCreateMemStorage ();
CvMemStorage *storage1 = cvCreateMemStorage ();
CvSeq *contours = 0;
//find contour in BInv
cvFindContours (BInv, storage, &contours, sizeof(CvContour), CV_RETR_LIST,CV_CHAIN_APPROX_NONE ,cvPoint(0,0));
//creating empty sequence of CvPoint
CvSeq* seq = cvCreateSeq(CV_SEQ_ELTYPE_POINT/*| CV_SEQ_KIND_SET | CV_SEQ_FLAG_SIMPLE*/,sizeof(CvSeq),sizeof(CvPoint),storage1);
//populating seq with all contours
for(; contours!=0; contours = contours->h_next)
for(int i=0;i<contours->total;i++)
{
CvPoint* p;
p = (CvPoint*)cvGetSeqElem (contours, i );
cvSeqPush(seq,p);
}
//bounding box and drawing
CvBox2D bbox=cvMinAreaRect2(seq, NULL );
cvEllipseBox(color,bbox,cvScalarAll(0),5,8,0);
hope this helps.
If you want to merge contours on the basis of distance apart then you can do something like this:
struct hash_pair {
template <class T1, class T2>
size_t operator()(const pair<T1, T2>& p) const
{
auto hash1 = hash<T1>{}(p.first);
auto hash2 = hash<T2>{}(p.second);
if (hash1 != hash2) {
return hash1 ^ hash2;
}
return hash1;
}
};
void findPixelsNearby(unordered_map<pair<int, int>,bool,hash_pair>&res, Point px,int pxlVal) {
for (int itr1 = (px.x) - pxlVal; itr1 <= (px.x) + pxlVal; itr1++) {
for (int itr2 = (px.y - pxlVal); itr2 <= (px.y) + pxlVal; itr2++) {
res[{itr1, itr2}] = true;
}
}
}
unordered_map<pair<int, int>, bool, hash_pair> createSets(vector<Point2f>Contour, int rect) {
unordered_map<pair<int,int>,bool,hash_pair>res;
for (auto tra : Contour) {
Point px = (Point)tra;
findPixelsNearby(res,px,rect);
}
return res;
}
//void drawContour(Mat& img, vector<Point2f>s1,int px,int py,int pz) {
// for (auto x : s1) {
// line(img, x, x, Scalar(px, py, pz), 4, 0);
//
// }
// resShow("temp",img,1);
//}
bool hasCommon(unordered_map<pair<int,int>,bool,hash_pair>s1, unordered_map<pair<int, int>, bool, hash_pair>s2){
for (auto x : s1) {
if (s2.find(x.first) != s2.end()) {
return true;
}
}
return false;
}
void MergeContours(Mat image, vector<Contour>&usableContours,int distance_considered, vector<Contour>& finalContours) {
int numberContours = usableContours.size();
vector<vector<int>>ids_for_contour_merge(numberContours);
vector<unordered_map<pair<int, int>, bool, hash_pair>>ContourSets;
vector<bool>boolVals(numberContours,false);
for (int i = 0; i < numberContours; i++) {
ContourSets.push_back(createSets(usableContours[i].points, distance_considered/2));
}
for (int i = 0; i < numberContours; i++) {
if (boolVals[i] == false) {
boolVals[i] = true;
for (int j = i+1; j < numberContours; j++) {
if (boolVals[j] == false) {
if(hasCommon(ContourSets[i], ContourSets[j])==true){
ContourSets[i].insert(ContourSets[j].begin(), ContourSets[j].end());
boolVals[j] = true;
ids_for_contour_merge[i].push_back(j);
j = i;
}
}
}
}
}
vector<bool>Visited(ids_for_contour_merge.size(), false);
for (int mr = 0; mr < ids_for_contour_merge.size(); mr++) {
if (Visited[mr] == false) {
vector<Point2f>temp=usableContours[mr].points;
if (ids_for_contour_merge[mr].size() > 0) {
for (int mc = 0; mc < ids_for_contour_merge[mr].size(); mc++) {
int valPtr = ids_for_contour_merge[mr][mc];
copy(usableContours[valPtr].points.begin(), usableContours[valPtr].points.end(), std::back_inserter(temp));
Visited[valPtr] = true;
}
}
else {
Visited[mr] = true;
}
Contour newCtr;
newCtr.points = temp;
finalContours.push_back(newCtr);
}
}
///////////////////////////////////////////////////////////////DRAWING CONTOURS
/*for (auto x : finalContours) {
cout <<"CONTOURS FINAL SIZE IS : " <<x.points.size()<<endl;
int px = 0;
int py = 0;
int pz = 0;
drawContour(image, x.points, ((px+rand())%255), ((py + rand()) % 255), ((pz + rand()) % 255));
}*/
//////////////////////////////////////////////////////////////////////////////
}
More On Github: https://github.com/HimanshuYadav117/Merge-Contours/blob/main/MergeContours.cpp

Creating a Linked list with Structs - C++

I was writing a program which could read an input file and store the read data in nodes linked by a "link list". However, I was getting a few errors:
In constructor List::List(), no match for 'operator =' in *((List*)this)->List::list[0] = 0
In constructor Polynomial::Polynomial(): no match for 'operator =' in *((Polynomial*)this)->Polynomial::poly = (operator new(400u), (<statement>), ...)
I have a feeling where I do: I try to access a certain node through an array is where I go wrong, however, I can't figure it out much.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
enum result{success, failure};
struct Node
{
double coefficient;
int power;
Node();
Node(double coef, int pwr);
};
struct List
{
Node *list[100];
//Default constructor
List();
};
Node::Node()
{
coefficient = 0;
power = 0;
}
List::List()
{
*list[0] = NULL;
}
Node::Node(double coef, int pwr)
{
coefficient = coef;
power = pwr;
}
class Polynomial
{
public:
Polynomial();
result multiply(Polynomial &p, Polynomial &q);
result add(Polynomial p, Polynomial &q);
void initialize(ifstream &file);
void simplify(Polynomial &var);
void print_poly();
~Polynomial();
private:
List *poly; //Store the pointer links in an array
Node first_node;
int val;
};
Polynomial::Polynomial()
{
*poly = new List();
}
Polynomial::void initialize(ifstream &file)
{
int y[20];
double x[20];
int i = 0, j = 0;
//Read from the file
file >> x[j];
file >> y[j];
first_node(x[j], y[j++]); //Create the first node with coef, and pwr
*poly->list[i] = &first_node; //Link to the fist node
//Creat a linked list
while(y[j] != 0)
{
file >> x[j];
file >> y[j];
*poly->list[++i] = new Node(x[j], y[j++]);
}
val = i+1; //Keeps track of the number of nodes
}
Polynomail::result multiply(Polynomial &p, Polynomial &q)
{
int i, j, k = 0;
for(i = 0; i < p.val; i++)
{
for(j = 0; j < q.val; j++)
{
*poly->list[k] = new Node(0, 0);
*poly->list[k].coefficient = (p.poly->list[i].coefficient)*(q.poly->list[j].coefficient);
*poly->list[k++].power = (p.poly->list[i].power)+(q.poly->list[j].power);
}
}
val = k+1; //Store the nunber of nodes
return success;
}
Polynomial::void simplify(Polynomial &var)
{
int i, j, k = 0;
//Create a copy of the polynomial
for(j = 0; j < var.val; j++)
{
*poly->list[j] = new Node(0, 0);
*poly->list[j].coefficient = var.poly->list[j].coefficient;
*poly->list[j].power = var.poly->list[j].power;
}
//Iterate through the nodes to find entries which have the same power and add them, otherwise do nothing
for(k = 0; k < var.val; k++)
{
for(i = k; i < var.val;)
{
if(*poly->list[k].power == var.poly->list[++i].power)
{
if(*poly->list.power[0] == 0)
{
NULL;
}
else
{
*poly->list[k].coefficient = *poly->list[k].coefficient + var.poly->list[i].ceofficient;
var.poly->list[i] = Node(0, 0);
}
}
}
}
}
Polynomial::void print_pol()
{
int i = 0;
for(i = 0; i < temp.val; i++)
{
cout << "Coefficient: " << temp.poly->list[i].coefficient << ", and " << "Power: " << temp.poly->list[i].power << endl;
}
}
The problem is a wrong dereference. Line 34 should probably be
list[0] = NULL; // remove the *
You try to assign the value NULL to a variable of the type Node, but you probably mean a pointer to Node.
The very same is true in line 63.
In addition, line 66 sould probably b:
void Polynomial::initialize(ifstream &file) // start with return type

Annoying, transitive-const-ness issue in D

I'm running across a very annoying problem regarding transitive const in D.
I have the code below:
struct Slice(T)
{
T items;
size_t start, length, stride;
this(T items, size_t start = 0, size_t length = size_t.max, size_t stride=1)
{
if (length == size_t.max)
{ length = 1 + (items.length - start - 1) / stride; }
this.items = items;
this.start = start;
this.length = length;
this.stride = stride;
}
Slice!(T) opSlice(size_t a, size_t b)
{
// Everything is fine here
return Slice!(T)(items, start + a * stride, b - a, stride);
}
const(Slice!(T)) opSlice(size_t a, size_t b) const
{
// ERROR! 'items' is const(T), not T.
return const(Slice!(T))(items, start + a * stride, b - a, stride);
}
}
The trouble I'm running to is that, pretty much, the data types const(Slice!int) and Slice!const(int) and const(Slice!const(int)) are just... weird.
How do I overload opSlice above, to return a constant copy of the current slice which can subsequently be used like the original slice?
In other words, let's say I have:
void test(in Slice!(int[]) some_slice)
{
//...
}
void main()
{
auto my_slice = Slice!(int[])();
const my_const_slice = my_slice;
test(my_slice); // succeeds
test(my_const_slice); //succeeds
test(my_const_slice[0 .. 1]); // fails
}
The code above doesn't work. What is the best way of making it work? (I could of course always templatize test(), but then all the slice variations -- const(Slice!(Slice!const(int[]))) and such -- would grow exponentially, and confusingly so.)
Edit:
Is there a solution that works for structs and classes?
change the constructor to
inout this(inout T items, size_t start = 0, size_t length = size_t.max, size_t stride=1)
{
if (length == size_t.max)
{ length = 1 + (items.length - start - 1) / stride; }
this.items = items;
this.start = start;
this.length = length;
this.stride = stride;
}
the inout keyword was made for this, it lets the const-ness/immutability of a parameter propagate to the result
inout also works if Slice is a class:
class Slice(T)
{
T items;
size_t start, length, stride;
this(){}
inout this(inout T items, size_t start = 0, size_t length = size_t.max, size_t stride=1)
{
if (length == size_t.max)
{ length = 1 + (items.length - start - 1) / stride; }
this.items = items;
this.start = start;
this.length = length;
this.stride = stride;
}
inout(Slice!(T)) opSlice(size_t a, size_t b) inout{
return new inout(Slice!T)(items, start + a * stride, b - a, stride);
}
}
void test(in Slice!(int[]) some_slice)
{
//...
}
void main()
{
auto my_slice = new Slice!(int[])();
const my_const_slice = my_slice;
test(my_slice); // succeeds
test(my_const_slice);//succeeds
test(my_const_slice[0 .. 1]); // succeeds
}