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.
Related
So I'm making an addon for node.js as in: http://nodejs.org/api/addons.html#addons_wrapping_c_objects.
However: my class has a pthread that loops forever and performs callbacks via uv_async_send() as suggested in http://nikhilm.github.io/uvbook/threads.html.
This callback function needs to access non-static class variables, I do that by setting: async.data = (void*) this; and in the callback function: MyClass* obj = (MyClass*)(handle->data);, so that i can access the data via: obj->myvar.
What happens though, is that the callback function is called after the object has been destructed already. I'm wondering how to prevent this from happening, preferably without the need for extra javascript code.
In case you wonder why the callback needs to access member variables: it's a buffer that is filled by the seperate thread, which passed as argument to the javascript callback.
Thanks in advance.
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.
I rewriting some code that i written a long time ago.
The code is a class that start another worker thread with AfxBeginThread. When the thread ends, it needs to return it work to the calling class.
Actually when the thread ends it send a message by PostMessage with its results to the called class.
But this way is really dependent of MFC, and to do this my class have to implement all the MFC stuffs.
May be correct if instead of send a message it directly call a non-static method of this class ?
Rather than trying to call a method directly (which will introduce a whole new set of threading problems of its own), try using the native Win32 ::PostMessage() instead of the MFC implementation of the same function. Any thread can call ::PostMessage() to deliver a message to another thread safely.
It sounds as though you want to use regular threading primitives, not window messaging primitives.
Which version of AfxBeginThread are you using? If you pass it a class instance, you should be able to access the members of that class directly once you know its finished running. If you passed it a function pointer, you can pass any class pointer in with the lParam parameter, then use that as a communication context.
You just want to make sure that when you access the class you do it in a thread safe manner. If you wait till the thread has ended you should be fine. Otherwise you could use Critical Sections or Mutexes. See the MSDN article on thread synchronization primitives for more info.
I want to make a simple worker thread inside a same class. However, there are 3 major problems that I am facing, which are:
Definition of a thread function in class header.
Thread function call.
Called thread function format.
I am also confused to use either AfxBeginThread or CreateThread function call to pass multiple thread parameters. Can anyone please provide me a simple worker thread to run in MFC based on the 3 things that I have provided above?
Definition of a thread function in class header: It has to be a static member because the usual way of putting "this" in a hidden parameter doesn't work. Since you only get one parameter, you want the parameter to be a pointer to a struct, and one member of the struct can be "this" of the class instance that your static member can call.
Thread function call: Since the function that gets called is going to use MFC, it is easiest to have the caller call AfxBeginThread. Since you say the thread will be a worker thread, call the version of AfxBeginThread that is designed for worker threads (even if it doesn't matter much).
Called thread function format. MSDN describes AfxBeginThread and says what prototype must be used for the first parameter.
Ideally, you should never be using CreateThred. And if you're using MFC, you MUST use AfxBeginThread to for creating threads.
I've given some explanation here in this discussion: http://www.daniweb.com/forums/thread249210.html
CreateThread is mainly for UI Threads but is still preferred to use the second method for AfxBeginThread. Store a reference to the threads handle in the header not the thread.
HANDLE hThread;
then in source start your thread pointing to your proc:
CWinThread *pThread;
if(!(pThread = AfxBeginThread(ThreadProc, NULL, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED))) {
delete arr;
}
::DuplicateHandle(GetCurrentProcess(), pThread->m_hThread, GetCurrentProcess(), &hThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
pThread->ResumeThread();
You start it suspended so you can copy the handle to the one you have stored in header. this way you can use the stored handle to check on exitcode.
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++