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.
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 have a class Class in which there's a member property HANDLE handle to a thread (We can assume it is set to NULL at that point) . at some point , a method within Class dispatches one of it's own methods Class::threaded() (using another function that is external to the class itself, but it doesn't really matter here) with CreateThread(). The calling thread will then may continue to other function outside of Class.
As CloseHandle() must be called for the HANDLE returned from CreateThread() , I was wondering if calling it from Class::threaded() just before it returns would be a decent solution.
Two basic ways to deal with a thread. Commonly you're interested when the thread terminates, you'll need to keep the handle around so you can find out. And of course you'll close it after you detected termination. Or you don't care, fire-and-forget style, or have additional synchronization objects to signal that the thread function completed and/or you ask it to exit. In which case you simply close the handle as soon as you start it.
Do keep in mind that it is not necessary to keep the handle opened to keep the thread running, in case that's the source of the confusion.
You receive a handle to the thread so you can manage it. If there is no need to it, you can call CloseHandle right away.
Closing the HANDLE will have no terminate the thread, so, it's secure to close it if nothing from the thread is of interest to you.
You can close it as soon as you are through using it. Closing it has no effect on the thread. (The handle is reference counted by OS.)
My code calls a function from 3rd party library. Let's call this function SomeFunc
void SomeFunc(void (*callBack) (int));
As you can see SomeFunc takes a callback function parameter. Once SomeFunc is called, the calling thread will progress, and the library will execute the callback several time on a different thread -- passing it different status code.
My requirement is the thread that calls SomeFunc (aka main thread) should wait until certain status code is passed to the callback. So far I have something like this
CEvent *pEvt = NULL;
void myCallBack(int code) {
if(code == SOME_MAGIC_NUM) pEvt->SetEvent(); // signal thread waiting for this event obj they can continue
}
int main (int argc, char** argv) {
pEvt = new CEvent(FALSE, TRUE);
SomeFunc(myCallBack); // This doesn't block, main thread will progress to next line
WaitForSingleObject(pEvt, 5000); // wait here until 3rd party library call myCallBack with code SOME_MAGIC_NUM -- or if it doesn't after 5 seconds, continue
// do interesting stuff here..
return EXIT_SUCCESS;
}
Now this seem fine if I only do this on the main thread / main function like above. However if multiple thread can execute the code block in main above, my problem is they will share reference to the global pEvt variable, and it will mess up
What's the best code design approach I should take here? Ideally I would like to change the callback function signature to accept reference to the CEvent object, but since it's a 3rd party library I'm unable to do that.
You really want the equivalent of a closure in javascript. You can accomplish something similar by binding the function call to a new CEvent object every time. Take a look at std::bind1st or boost::bind.
See also this stackoverflow thread
You can only achieve this is the 3rd party provides a way to pass back a 'custom' argument to the callback. Well designed APIs allow to set up a callback and a void* value and the callback receives this argument when invoked. From this void* you can expand to anything you like, including objects and method calls, via unsafe casting. All solutions based on binding or member function address or whatever else ultimately boil down to the same issue: somehow the this* has to be passed back to the callback.
For an example, see BIO_set_callback: it allows you to set the callback and a callback arbitrary argument. Note that the callabck argument can be indirect, like for example in gnutls: the argument can be set as arbitrary data on the session via gnutls_session_set_ptr and then in the callback(s) it can be retrieved using gnutls_session_get_ptr. Your 3rd party may provide such an indirect method.
If the library does not offer such feature then you're stranded into hacks. For example you can have a collection of callbacks 'available', each one associated with a specific event (ie. different functions as address, although same code). You pick one callback and remove it from collection and place it, then wait for the event associated with that callback. When done, place the callback back into the available list. The size of the 'available' list is hard coided at compile time as you really need separate functions, one for each callback.
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 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++