//function creating my class and thread
extractor = new FeatureExtractor(receiveBufferCurrent);
HANDLE hth1;
unsigned uiThread1ID;
hth1 = (HANDLE)_beginthreadex(NULL,
0,
FeatureExtractor::ThreadStaticEntryPoint,
extractor,
CREATE_SUSPENDED,
&uiThread1ID);
//Header file
class FeatureExtractor
{
private:
float sensorData[200][10];
public:
FeatureExtractor(float receiveBufferCurrent[][10]);
~FeatureExtractor();
//Thread for parallel input and motion detection
static unsigned int __stdcall ThreadStaticEntryPoint(void * pThis);
void ThreadEntryPoint();
void outputTest();
};
FeatureExtractor::FeatureExtractor(float receiveBufferCurrent[][10])
{
memcpy(sensorData, receiveBufferCurrent, sizeof(sensorData));
}
unsigned __stdcall FeatureExtractor::ThreadStaticEntryPoint(void * pThis)
{
FeatureExtractor * pthX = (FeatureExtractor*)pThis;
pthX->ThreadEntryPoint();
return 1;
}
void FeatureExtractor::ThreadEntryPoint()
{
outputTest();
}
//output function
for (int i = 0; i < 200; i = i + 50)
{
std::cout << "-------------------------------------------------------------------------" << std::endl;
std::cout << "AccelX=" << sensorData[i][1] << ", AccelY=" << sensorData[i][2] << ", AccelZ=" << sensorData[i][3] << std::endl;
std::cout << std::endl;
std::cout << "MagX=" << sensorData[i][4] << ", MagY=" << sensorData[i][5] << ", MagZ=" << sensorData[i][6] << std::endl;
std::cout << std::endl;
std::cout << "GyroX=" << sensorData[i][7] << ", GyroY=" << sensorData[i][8] << ", GyroZ=" << sensorData[i][9] << std::endl;
std::cout << std::endl;
std::cout << "-------------------------------------------------------------------------" << std::endl;
}
I have some problem with accessing the float array "sensorData" inside a thread.
If I output the sensorData array inside the constructor everything is fine but if I access the array from inside my thread my array just contains -1.58839967e+038 which I guess means that I cannot access my array in this way from a thread.
What am I doing wrong?
I got the thread code from a tutorial which accesses class member variables in the same way although just integers not multi dimensional arrays.
I tried to minimize the length of my code snippets while keeping the important parts, I'm thankful for anybody taking the time to analyze my code!
I found the solution myself now.
WaitForSingleObject(hth1, INFINITE);
Once I waited for my thread the issue has been resolved.
The issue occurred because I deleted my class before it could finish execution.
It also worked to simple remove the delete statement.
Related
I am trying to write my own c++ wrapper class for linux using pthreads. The class 'Thread' is supposed to get a generic lambda to run in a different thread and abstract away the required pthread calls for that.
This works fine if the lambdas don't capture anything, however as soon as they capture some shared variables the behaviour seems to become undefined depending on whether or not the template types of two threads are the same or not. If both Thread objects caputre the same types (int and int*) it seems to (probably accidentally) work correctly, however as soon as i pass (e.g. like in my example) an integer A 'aka. stackInt' and an int ptr B 'aka. heapInt' to Thread 1 and only the int ptr B to Thread 2 i get a segfault in Thread 2 while accessing int ptr B.
I know that it must have something to do with the fact that each thread gets its own copy of the stack segment however i cant wrap my head around how that interferes with colsures capturing variables by refernce and calling them. Shouldn't the int ptr B's value point to the same address in each copy of it on the stack? How does the adress get messed up? I really can't wrap my head around whats the exact issue here..
Can anyone help me out here? Thank you in advance.
Here is the full example code:
class 'Thread'
// thread.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
// ******************************* //
// THREAD CLASS //
// ******************************* //
template <typename C>
class Thread
{
private:
C &m_closure;
pthread_t m_thread;
public:
Thread<C>(C &&closure)
: m_closure(closure),
m_thread()
{}
void start()
{
pthread_create(&m_thread, NULL, &Thread::threadFunction, (void *)this);
}
void join()
{
pthread_join(m_thread, NULL);
}
private:
void callbackOnInstance()
{
m_closure();
}
static void * threadFunction(void *);
};
template <typename C>
void * Thread<C>::threadFunction(void *caller)
{
Thread<C> *callerObject = (Thread<C> *)caller;
callerObject->callbackOnInstance();
return nullptr;
}
main() / testing
// main.cpp
// ******************************* //
// TESTING //
// ******************************* //
#define SLEEP_SEC(_sec) usleep((long)(1000 * 1000 * (_sec)))
#include "thread.h"
#include <iostream>
#include <string>
int main(int argc, char **argv)
{
int stackInt = 0;
int *heapInt = new int(0);
// every second each thread increments them, 0.5 s apart from each other
Thread thread1([&]()
{
while(true)
{
SLEEP_SEC(1);
std::cout << "thread #1:" << std::endl;
stackInt += 1;
std::cout << "stack int: " << stackInt << " [" << &stackInt << "]" << std::endl;
*heapInt += 1;
std::cout << "heap int: " << *heapInt << " [" << heapInt << "]" << std::endl;
}
});
thread1.start();
Thread thread2([&]()
{
SLEEP_SEC(0.5);
while(true)
{
SLEEP_SEC(1);
std::cout << "thread #2:" << std::endl;
// if stackInt doesn't get referenced ...
//stackInt += 1;
//std::cout << "stack int: " << stackInt << " [" << &stackInt << "]" << std::endl;
// ... i get a segfault here
*heapInt += 1;
std::cout << "heap int: " << *heapInt << " [" << heapInt << "]" << std::endl;
}
});
thread2.start();
thread1.join();
thread2.join();
}
You've got undefined behaviour, since the lambda objects are actually destroyed immediately after the constructor of Thread completes. To see this, instead of a lambda you could pass an object that prints a message in the destructor:
struct ThreadFunctor
{
int& stackInt;
int* heapInt;
ThreadFunctor(int& si, int* hi)
: stackInt(si),
heapInt(hi)
{
std::cout << "ThreadFunctor created: " << this << '\n';
}
~ThreadFunctor()
{
std::cout << "ThreadFunctor destroyed: " << this << '\n';
}
void operator()() const
{
using namespace std::chrono_literals;
while (true)
{
std::this_thread::sleep_for(1s);
std::cout << "thread #1:" << std::endl;
stackInt += 1;
std::cout << "stack int: " << stackInt << " [" << &stackInt << "]" << std::endl;
*heapInt += 1;
std::cout << "heap int: " << *heapInt << " [" << heapInt << "]" << std::endl;
}
}
};
Thread thread1(ThreadFunctor{stackInt, heapInt});
std::cout << "before start\n";
thread1.start();
The following output is guaranteed for every standard compliant C++ compiler (modulo addresses):
ThreadFunctor destroyed: 0000006E3ED6F6F0
before start
...
Furthermore the join operation only completes after the operation on the background thread has been completed, so because of the infinite loops your program won't terminate. You need some way of notifying the background threads to actually return instead of continuing forever.
Note that the standard library already contains the exact logic you're trying to implement here: std::thread or std::jthread for a implementation with builtin way of informing the background thread of a termination request.
int main()
{
using namespace std::chrono_literals;
int stackInt = 0;
int* heapInt = new int(0);
// every second each thread increments them, 0.5 s apart from each other
std::jthread thread1{ [=](std::stop_token stopToken, int& stackInt)
{
using namespace std::chrono_literals;
while (!stopToken.stop_requested())
{
std::this_thread::sleep_for(1s);
std::cout << "thread #1:" << std::endl;
stackInt += 1;
std::cout << "stack int: " << stackInt << " [" << &stackInt << "]" << std::endl;
*heapInt += 1;
std::cout << "heap int: " << *heapInt << " [" << heapInt << "]" << std::endl;
}
}, std::ref(stackInt) }; // thread started immediately
std::this_thread::sleep_for(10s);
thread1.request_stop();
thread1.join();
}
I am new to C++ and I really need some help on this. I am trying to create a structure to interface with the GSL Monte-Carlo algorithms (a fact that is really not important for this example). I have searched all of the C++ tutorials, the stackoverflow posts and the GSL documentation with no luck. I am using the armadillo package for matrix manipulation; it is very robust. I am unable to use a dynamic array within the structure, as per the documentation, so I am trying to find a way to make my structure variable *M point to the values in my array *L[]. I am sure that this would be better with a vector but 1) the rest of the code (in bad form) uses pointers already, and 2) I am looking at this as a learning experience. I am surprised that the addresses for *M and *L[] are not the same in my code. I am also, less importantly, surprised that my std::cout prints a different number of spaces for each line. The code exits before printing the last std::cout as shown in the output below.
Thanks for your help!
#include "pch.h"
#include "stdio.h"
#include "complex"
#include "new"
#include "armadillo"
using namespace arma;
class Link
{
public:
arma::Mat<cx_double>::fixed<3, 3>* dir[4]; // pointer to directional SU(3) matrices
Link(); // default constructor
};
Link::Link() // default constructor - all directional matrices are the identity
{
for (size_t hcount = 0; hcount < 4; hcount++)
{
dir[hcount] = new arma::Mat<cx_double>::fixed<3, 3>{ fill::eye }; // create directional matrix in direction hcount
}
}
struct Param
{
Link* M;
};
int main()
{
const int size = 10;
Param* Parameters = new Param{ NULL };
Link* L[size];
arma::Mat<cx_double>::fixed<3, 3> One{ fill::eye };
for (size_t hcount = 0; hcount < 10; hcount++)
{
L[hcount] = new Link();
*L[hcount]->dir[1] = *L[hcount]->dir[1] + hcount * One; // Make each array element #1 unique
}
Parameters->M = L[0];
std::cout << "&L = " << &L << std::endl;
std::cout << "&Parameters->M = " << &Parameters->M << std::endl; // surprised that addresses are not the same
std::cout << std::endl;
std::cout << "&L[0] = " << &L[0] << std::endl;
std::cout << "&Parameters->M[0] = " << &Parameters->M[0] << std::endl;
std::cout << std::endl;
std::cout << "&L[5] = " << &L[5] << std::endl;
std::cout << "&Parameters->M[5] = " << &Parameters->M[5] << std::endl;
std::cout << std::endl;
std::cout << "&L[5]->dir[1] = " << &L[5]->dir[1] << std::endl;
std::cout << "&Parameters->M[5].dir[1] = " << &Parameters->M[5].dir[1] << std::endl;
std::cout << std::endl;
std::cout << "*L[5]->dir[1] = " << *L[5]->dir[1] << std::endl; // This works
std::cout << "*Parameters->M[5].dir[1] = " << *Parameters->M[5].dir[1] << std::endl; // This does not
std::cout << std::endl;
}
OUTPUT
&L = 0024F7CC
&Parameters->M = 004EEFD8
&L[0] = 0024F7CC
&Parameters->M[0] = 004E0578
&L[5] = 0024F7E0
&Parameters->M[5] = 004E05C8
&L[5]->dir[1] = 004E50C4
&Parameters->M[5].dir[1] = 004E05CC
*L[5]->dir[1] = (+6.000e+00,+0.000e+00) (0,0) (0,0)
(0,0) (+6.000e+00,+0.000e+00) (0,0)
(0,0) (0,0) (+6.000e+00,+0.000e+00)
*Parameters->M[5].dir[1] =
&L is the adress of L, so it's the adress of the pointer to the first element not the adress of the first elemenr itself. Same for & Parameters->M. That is the adress of thd the Member M from Parameters. You want to compare L[0] with Parameters->M except when M should not point to the element that L[0] refers to but to the start of the array itself, then you want to compare it with L. But then you also have to change the assignment.
I find it a bit weird that you use an array of pointers. Just use an array of Links.
I have a variable in file tracker.hpp:
namespace TRIALS
{
static thread_local int a = -1;
}
I have another class in file called EMP in ema.hpp/ema.cpp
namespace Algo
{
class EMP
{
public:
void Sample();
};
}
namespace Algo
{
void EMP::Sample()
{
std::cout << "model " << std::this_thread::get_id() << " " << &TRIALS::a << " " << TRIALS::a << std::endl;
}
}
Then my main file I have
auto model = Algo::EMP();
void Simulate(const int a)
{
TRIALS::a = a;
model.Sample()
std::cout << "worker " << std::this_thread::get_id() << " " << &TRIALS::a << " " << TRIALS::a << std::endl;
}
int main()
{
std::cout << &TRIALS::a << std::endl;
const int nthreads = 1;
std::cout << "main " << std::this_thread::get_id() << " " << &TRIALS::a << " " << TRIALS::a << std::endl;
std::vector<std::thread> threads;
for(int i=0; i<nthreads; ++i)
{
threads.emplace_back(&Simulate, i);
}
for(auto &thread : threads)
{
thread.join();
}
std::cout << "main " << std::this_thread::get_id() << " " << &TRIALS::a << " " << TRIALS::a << std::endl;
return 0;
}
I am just running one thread for debugging but this is the output:
0x7f9540b621d8
main 140279012532800 0x7f9540b621d8 -1 (As expected)
model 140278985606912 0x7f953f1b469c -1 (Shouldn't this be 0??)
worker 140278985606912 0x7f953f1b4698 0 (As expected)
main 140279012532800 0x7f9540b621d8 -1 (As expected)
I was under the impression that each thread has it's own local copy of TRIALS::a. The a in model correctly gets incremented but when it returns from the function in the same thread, the value is still 0. I am printing out the thread ids and the address of a for good measure and I am seeing that there are actually 3 different versions of TRIALS::a despite only two total threads.
As a bonus question, what is the difference between static thread_local int a and thread_local int a ?
In your example static makes that thread_local object use internal linkage, so that each translation unit (.cpp file) has its own copy of the variable.
See storage class specifiers for details:
The thread_local keyword is only allowed for objects declared at namespace scope, objects declared at block scope, and static data members. It indicates that the object has thread storage duration. It can be combined with static or extern to specify internal or external linkage (except for static data members which always have external linkage), respectively, but that additional static doesn't affect the storage duration.
I.e. you may like to drop that static keyword, so that you only have one copy of the object in the entire application. In the header file do:
namespace TRIALS {
extern thread_local int a;
}
And in one of the .cpp:
thread_local int TRIALS::a = -1;
In C++17, you can make the variable inline to avoid having to provide its definition in a .cpp:
namespace TRIALS {
inline thread_local int a = -1;
}
This is my third question on this topic, Instead of asking a new question in the comments I thought it would be better to start a new thread.
The full code can be found here:
C++ CvSeq Accessing arrays that are stored
And using the following code I can display the most recent vector that has been added to the RECT array(Note that this is placed inside of the for loop):
RECT& lastRect = detectBox->back();
std::cout << "Left: " << lastRect.left << std::endl;
std::cout << "Right: " << lastRect.right << std::endl;
std::cout << "Top: " << lastRect.top << std::endl;
std::cout << "Bottom: " << lastRect.bottom << std::endl;
What I am now trying to do is create a loop outside of this for loop that will display all of the vectors present in detectBox. I havent been able to determine how many vectors are actually present in the array, and therefore cannot loop through the vectors.
I tried using the following:
int i = 0;
while ((*detectBox)[i].left!=NULL)
{
std::cout << "Left: " << (*detectBox)[i].left << std::endl;
std::cout << "Right: " << (*detectBox)[i].right << std::endl;
std::cout << "Top: " << (*detectBox)[i].top << std::endl;
std::cout << "Bottom: " << (*detectBox)[i].bottom << std::endl;
i++;
}
And have also tried playing around with sizeof(*detectBox) , but only have an answer of 32 being returned...
Okay, you are using the wrong terms here. The variable detectBox is a vector (or rather a pointer to a vector it seems). There are three ways to iterate over it (I'll show them a little later). It is not an array, it is not an array of vectors. It is a pointer to a vector of RECT structures.
Now as for how to iterate over the vector. It is like you iterate over any vector.
The first way is to use the C way, by using indexes:
for (unsigned i = 0; i < detectBox->size(); ++i)
{
RECT rect = detectBox->at(i);
std::cout << "Left: " << rect.left << std::endl;
...
}
The second way is the traditional C++ way using iterators:
for (std::vector<RECT>::iterator i = detectBox->begin();
i != detectBox->end();
++i)
{
std::cout << "Left: " << i->left << std::endl;
...
}
The last way is to use range for loops introduced in the C++11 standard:
for (RECT const& rect : *detectBox)
{
std::cout << "Left: " << rect.left << std::endl;
...
}
The propblem with your attempt of the loop, with the condition (*detectBox)[i].left!=NULL is that the member variable left is not a pointer and that when you go out of bounds you are not guaranteed to have a "NULL" value (instead it will be indeterminate and will seem random).
This may be very simple but I am confused!
I am getting segmentation fault when extracting information from a pointer to a pointer. See the cout section in main(). Any help will be appreciated.
Thanks..
Sen
#include <stdlib.h>
#include <iostream>
typedef struct{
int hour;
int minute;
} Time;
Time* GetNextTime(void)
{
Time *p_time = new Time;
return p_time;
}
void GetTime( Time **sometime )
{
int length = 10;
sometime = new Time*[length];
for(int i=0; i<length; i++)
{
sometime[i] = GetNextTime();
sometime[i]->hour = rand()%24 ;
sometime[i]->minute = rand()%60;
std::cout << "Entered times " << sometime[i]->hour << " hour " << sometime[i]->minute << " minutes " << std::endl;
}
}
int main()
{
Time** _time;
GetTime( _time );
//here is the question
// I cant print them from original _time
for( int i=0; i<10; i++)
std::cout << " Print times " << (*_time)[i].hour << " hour " << (*_time)[i].minute << " minutes " << std::endl;
}
You're passing sometime by value, not by reference so it remains uninitialized. Change GetTime to the following:
void GetTime( Time ** &sometime ) //& means pass by reference
Because you're creating an array of pointers, you can use array notation to access them during printing as well.
std::cout << " Print times " << _time[i]->hour << " hour "
<< _time[i]->minute << " minutes " << std::endl;
Unless an argument is explicitly labelled as using a reference it is passed by value in C++. Thus, assigning to sometime in GetTime() has no effect on _time in main().
My strong advice is not to us explict memory allocation but use containers, e.g. std::vector<T>, instead. You'd still need to pass the container by refernence, however.
In main
It should be
Time *_time;
GetTime(&_time)
And then cout should be done with _time instead of *_time