I have Runnable class. In which, following functions I use to start new thread:
start()
{
status_ = RUNNING;
mythread_ = boost::thread(boost::ref(*this)); // Line 2
}
I have Controller class derived from Runnable.
and I want to create thread for Controller using start() function
So, In Controller start function,
I use:
controller_->start()
to create a new thread;
But which eventually leads to segmentation fault at Line 2.
Any idea what could have been gone wrong?
I remember sometimes not specifying the thread library to the compiler has resulted in segfault. Try adding -pthread argument to the compiler if you're using unix. It seems though that it's not needed on latest linux/boost/gcc anymore.
The object's address is only available from within the member function as the this pointer and most uses of this are implicit.
Alternatively, you can make the start() function, friend of the class and directly sending reference of the object to your new thread.
Related
I wanted to show a problem I’m having while invoking functions of an instantiated class in C++.
I’m using a separate thread to listen to a TCP socket, so when data comes, I want to call a function to start doing tasks. I’m using process.h library and _beginthread(socket_init,0,NULL); to start the thread with socket_init() function, which starts the listener.
To put you into situation, right before the thread initialization call, I have this:
CPhoneDlg dlg = new CPhoneDlg;
m_pMainWnd = &dlg;
This class has this function declared:
CTapiLine* CPhoneDlg::GetActiveLine() {...}
So the point of all this, is to be able to call GetActiveLine() from the function that is being executed in the separate thread.
For that I tried to do this:
CTapiLine* line = dlg.GetActiveLine();
But it just doesn’t know what dlg is, showing "identifier not declared" when I try to compile the code.
Is there any way to make dlg object visible so its methods become "invokable" by the separate thread?
I had to figure out almost this exact issue just the other day, so I think I can help. You need to pass an object to your class into the thread function. See the following code:
DWORD WINAPI PhoneThread(LPVOID lpParam)
{
CPhoneDlg *phoneDlg = reinterpret_cast<CPhoneDlg *>(lpParam);
CTapiLine* line = phoneDlg.GetActiveLine();
}
And instantiate the thread like this (from within your class!):
CreateThread(NULL, 0, PhoneThread, this, 0, NULL);
As long as GetActiveLine() is public, you should be able to make it work like this.
What I am doing is passing in a pointer to the main class as an LPVOID. When you get into the thread, you can use reinterpret_cast to cast it back to the type of the main class. Now, you have a pointer to the class from within your thread and you can access public functions and variables.
I'm trying to reverse-Engineer and fix a Win32 Console Application which is throwing an unhandled exception.
I've got 32 instances of a class running in threads. These "Service" threads should each create / delete a unique instance of CMessage regularly and each of these CMessage objects is declared private in the Service class.
When I run the application in the debugger (I'm using Visual Studio 2005) the watch window for the CMessage indicates that right before a CMessage member function is invoked the address of CMessage changes to 0x00000000 - the cause of the exception.
There is no straightforward explanation that i can see for why this happens. Nothing untoward appears to be happening between the previous line of code and this one, so my suspicion is that somehow each thread is mistakenly referencing the CMessage object from one of the other threads in some cases (as at some point during the threads lifetime the CMessage object for that thread is deleted).
My question is: What is the best way to make sure that these CMessage objects are absoloutely thread safe and can't be modified / deleted from anywhere, except for the current class scope? I thought that this was what private was for, but I'm not entirely sure now. One thing I thought about doing was referring to the CMessage object as follows:
this->myCMessage;
as opposed to just:
myCMessage;
Would this make any difference?
Well the private tag in class is just a syntactic sugar, it won't change how the code is generated.
If you're calling a member function and right after that the class member goes to NULL, the problem might be that the member function somehow deletes the CMessage object. Note though, that if the CMessage object is allocated in stack, the problem probably is not that case.
Another problem might be that the CService object gets destroyed(thread gets terminated) before it completes the current function accessing the CMessage object.
i have an encoder class with lots of methods . this is a subclass of Qthread. i am new to multi-threading and
trying to understand how this class is
threading its methods
... i understand to thread a method it has to be in a subclass of qthread. and the run of this implements the threaded code for this class. And the thread starts only when a call to start method on the object of this class is made.
Question : firstly what do you infer
from the this run implementation
void Encoder::run(void)
{
VERBOSE(VB_DEBUG, "Encoder::run");
if (WILL_PRINT(VB_DEBUG))
print_stats_timer_id = QObject::startTimer(kEncoderDebugInterval);
health_check_timer_id = QObject::startTimer(kEncoderHealthCheckInterval);
if (init())
exec();
else
VERBOSE(VB_ERROR, "Encoder::run -- failed to initialize encoder");
QObject::killTimer(health_check_timer_id);
if (print_stats_timer_id)
QObject::killTimer(print_stats_timer_id);
cleanup();
}
Question: what does thread context mean in
relation to its methods .
also
Question: what would happen If a method of this
class is called before this class's
thread has started
The class you have written creates a thread and initializes a QObject::timer. It then goes on to call a user defined init() function then the QThread::exec() function.
My guess is that you intended that exec() would be a user defined function where the actual work is to occur. Be aware that QThread::exec() processes the thread's Qt Event Queue.
Also, on some platforms you may get an "Error creating timer from thread" warning message. I've encountered this error on Windows when the code executed fine on Linux
Also, be aware that your timer will never occur if you do not call the QThread::exec() function or QApplication::processEvents() from within your thread.
Thread context in Qt is the same as any other thread concept. That is, all memory is shared between the threaded code (entered at this point in your "run()" function). And any other context which calls into your object. If this object may ever be executing in a thread and accessed from outside of the thread you must protect the shared data.
Because all data is shared between thread contexts (it's a shared memory multiprocessing model) there is no problem with calling functions before/after/during thread execution. Given that:
The object is fully constructed before you call any method. This is not special to threads, necessarily, unless the object is created in a thread.
Any data member is protected with a mutex lock (I eluded to this in #2). QMutexLocker is a handy stack based RAII way of dealing with mutex locks in Qt.
I believe I fully answered your question here, so I'll go ahead and link to RAII and threading articles I have written on another site, just for further reference.
Edit: specificity about threading scenarios:
class MyThreadedClass : public QThread
{
MyThreadClass(const boost::shared_ptr<SomeOtherClass> &t_object)
: m_object(t_object) {}
void doSomething()
{
// Depending on how this method was called (from main, from internal thread)
// will determine which thread this runs on, potentially complicating thread
// safety issues.
m_object->someThing();
}
void run()
{
// I'm now in a thread!
m_object->someFunction(); // oops! The call to someFunction is occurring from
// a thread, this means that SomeOtherClass must be
// threadsafe with mutex guards around shared
// (object level) data.
// do some other stuff
}
};
int main()
{
MyThreadClass thread(someobjectfromsomewhere);
thread.start(); // MyThreadClass is now running
thread.doSomething(); // The call to doSomething occurs from main's thread.
// This means 2 threads are using "thread", main
// and "thread"'s thread.
// The call to thread.doSomething hits Thread.m_object, which means that
// now multiple threads are also accessing m_object ("thread" and "main").
// This can all get very messy very quickly. It's best to tightly control
// how many threads are hitting an object, and how
}
NOTE: It would be a good idea to investigate QFuture, which is designed to handle this kind of asynchronous task, like an encoder, that you are looking at QFuture will avoid some of the potential threading issues of shared data and deadlocks.
I'm totally new to programming with threads, and since the class is using QThreads, I'm wondering why I cannot call a QThread's start function from within itself and have its run function start executing independently of another thread (the program seems to crash when I do this). Instead, I have to call the start function from wherever the object was declared. Why is this?
Some code:
class ClassWithThread : public QThread
{
public:
ClassWithThread() {}
someFunction() {start();}
run()
{
//do some stuff here
}
}
That is basically what my class does. When I call someFunction the program crashes. If I remove the start statement from someFunction though, and call start from outside the program, then it works fine.
QThread should be derived only if you want to extend thread capability, not to specialize it for your job like this. This article would help you to understand the use of QThread.
So you must create a QThread and start it from outside and then move an object to it that will do the job. Read this example: http://labs.qt.nokia.com/2006/12/04/threading-without-the-headache/
Hope that helps to avoid this kind of problem
I am just trying to understand some source code written in C++. I am a bit familiar
with C++, however, the following code sequence is absolutley new to me. A guess would be
that here I register some thread routine with the kernel, ptest->Run(). Could that be right?
static unsigned int __stdcall ThreadProc(void *lParameter)
{
CTest *ptest;
ptest= (Ctest *)lParameter;
ptest->Run();
return 0;
}
CTest::CTest(int n)
{
...
}
A bit simplified but a thread is a function, in this case ThreadProc. When the thread starts, the function is called and when the function exits the thread dies.
In this case, someone has started a thread with CreateThread, begin_thread or something else and passed in a pointer to a class called CTest as an argument. The thread then casts it back to a CTest* (as you can see the argument is delivered by the CreateThread API as a more generic void*) and calls the CTest::Run method before exiting.
Edit: Also, except for the "__stdcall" declaration, this is not very Windows specific. Threads in C and C++ works more or less like this on all OSes.
This is a function signature that would be used to define a function that is exported from a DLL or used as a callback function. In this case it is probably going to be used a the main loop of a worker thread.
the __stdcall keyword indicates that the function call is passed on the stack using the stdcall calling convention in Windows (same as used by methods exported from the Win32 API)
OOPS: this link doesn't play nice with markdown http://msdn.microsoft.com/en-us/library/zxk0tw93(VS.80).aspx
Not quite. This is your thread function:
static unsigned int __stdcall ThreadProc(void *lParameter)
It will be executed an different thread than whatever caused it. Calling code creates an object of type CTest, creates a thread that runs ThreadProc, which in turn runs ptest->Run();
ThreadProc is just a convenience wrapper to launch ptest->Run(). (Because otherwise it is kinda hard to use pointers to member functions)
What OS? Looks like a Windows sample, if so begin_thread(), or CreateThread or...several
The code you show declares a pointer to a CTest class object, converts the input parameter into one of those, then calls its run method.
The why this is done is the tricky part. Normally you wouldn't write code like this, however, the profile of ThreadProc is that of a thread's main entry point. For one of those, Windows doesn't give you any choice for the parameter profile of it, and it can't be a class member.
What you have there is fairly standard code to convert a thread entry-point callback from the Windows' required form into a class method call.
For a full discussion of this, see my (accepted) answer for the question: Passing Function pointers in C++