I am trying to develop a embedded HW simulator by Visual studio 2010 with WINAPI.
I met problem when I tried to emulate interrupt...
The interrupt behavior acts as follows...
while a threadA is working and meanwhile there comes an interrupt,
so threadA will be hold and jumps to execute the ISR function, after
the ISR function has been done, threadA can be resumed and keep working...
I tried to simulate this action by multithread
so there is a thread called interrupt-thread, which will suspend threadA and
do the ISR operation and then resume threadA, just like the below code...
but the problem is that my code will be stucked when calling sespendthread()
the previous printf("a") can be seen, but the printf("b") can not...
Is there any other ways to simulate interrupt with MSDN?
I considered about using singals and signalhandler to solve this question,
but it looks like windows signal can not be sent to specific thread,
only can be sent to specific process...
HANDLE thd_main;
HANDLE thd_int;
HANDLE Array_Of_Thread[2];
thd_main(){
while(1){
/* polling for jobs and do specific operation */
}
}
thd_int(){
while(1){
if (WaitForSingleObject(g_timer, infinite) == WAIT_TIMEOUT){
printf("a");
suspendthread(thd_main);
printf("b");
/* ISR operation */
resumethread(thd_main);
}
}
}
int main()
{
thd_main = CreateThread( NULL, 0,
Thread_main, NULL, 0, NULL);
thd_int = CreateThread( NULL, 0,
Thread_int, NULL, 0, NULL);
Array_Of_Thread[0] = thd_main;
Array_Of_Thread[1] = thd_int;
WaitForMultipleObjects( 3, Array_Of_Thread_Handles, TRUE, INFINITE);
closehandle(thd_main);
closehandle(thd_int);
return 0;
}
You should NOT use Suspend/ResumeThread to do thread synchronization!
Mainly these functions are present for debugging purpose. See MSDN documentation
See documentation for SuspendThread :
This function is primarily designed for use by debuggers It is not
intended to be used for thread synchronization.
The main problem is that you never know were you block a thread. Maybe it just uses resources that are locked by this thread. Than you may get deadlocks. Specially in the thread start phase and using CRT objects may cause such deadlock problems. But even if you use your synchronization objects you may fail.
Related
#define SW1 RB5
int IOFlag = 2; //while in out
void SW(){
if(!RB5)
__delay_ms(50);
while(!RB5);
__delay_ms(50);
IOFlag++;
}
void main(){
SW();
while(IOFlag % 2 != 0){
SW();
//some routines..
}
}
I used pic16f73, RB5 input use for switch.
When some of the routine is running, switch is not operating properly.
It is possible if you use the interrupt. However I don't know how to use it properly.
You need to understand the difference between polling and interrupts.
With polling (what you appear to be doing), you periodically check the state of some "thing" and act on it.
With interrupts, the "thing" happening causes your main thread of execution to be suspended, and an interrupt service routine (ISR) run.
Polling has the disadvantage of potentially long latency, the time between the thing happening and you finding out about it. In fact, you can even lose events if the thing is a momentary switch for example - you switch it on then off then, when the code checks for it, it's off.
Now you can still use polling if you wish, provided you understand these implications. Sometimes the easiest solution is to poll more often.
For example, if one of your //some routines.. jobs is a long running loop, you can poll from within there:
for (int i = 0; i < numThings; i++) {
doSomethingQuickWitn (thing[i]);
SW(); // Poll here as well
}
// Rather than here.
However, for _minimal latency, using interrupts is usually better and is reasonably simple once you wrap your head around the concept.
Your ISR (which will run on the given event, interrupting the main thread of execution) simply has to store the fact that the event has happened and communicate that to your main thread somehow.
For situations where you don't care how many times the event has happened, a flag will do the job. Your ISR simply sets the flag and your main thread of execution checks it periodically to see if it's been set, then clears it (with interrupts disabled so as to avoid race conditions). That would be something like (pseudo-code):
global val switchHit = false;
main:
interrupt (7, intFn) // call intfn() on interrupt 7
while true:
disableInts() // disallow interrupts for a short while
if switchHit:
handleSwitch() // switch was hit, do something (quickly)
switchHit = false // mark as not hit
enableInts() // and re-allow interrupts
doLotsOfOtherStuff()
intfn:
switchHit = true // notify main
Note that I'm not worry about race conditions within the ISR, interrupts are generally disabled automatically there.
More complicated information transfer may involve a count rather than a flag, or even a message queue of some sort, flowing from the ISR to the main thread of execution.
what is the rigth way to close Thread in Winapi, threads don't use common resources.
I am creating threads with CreateThread , but I don't know how to close it correctly in ,because someone suggest to use TerminateThread , others ExitThread , but what is the correct way to close it .
Also where should I call closing function in WM_CLOSE or WM_DESTROY ?
Thx in advance .
The "nicest" way to close a thread in Windows is by "telling" the thread to shutdown via some thread-safe signaling mechanism, then simply letting it reach its demise its own, potentially waiting for it to do so via one of the WaitForXXXX functions if completion detection is needed (which is frequently the case). Something like:
Main thread:
// some global event all threads can reach
ghStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// create the child thread
hThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
//
// ... continue other work.
//
// tell thread to stop
SetEvent(ghStopEvent);
// now wait for thread to signal termination
WaitForSingleObject(hThread, INFINITE);
// important. close handles when no longer needed
CloseHandle(hThread);
CloseHandle(ghStopEvent);
Child thread:
DWORD WINAPI ThreadProc(LPVOID pv)
{
// do threaded work
while (WaitForSingleObject(ghStopEvent, 1) == WAIT_TIMEOUT)
{
// do thread busy work
}
return 0;
}
Obviously things can get a lot more complicated once you start putting it in practice. If by "common" resources you mean something like the ghStopEvent in the prior example, it becomes considerably more difficult. Terminating a child thread via TerminateThread is strongly discouraged because there is no logical cleanup performed at all. The warnings specified in the `TerminateThread documentation are self-explanatory, and should be heeded. With great power comes....
Finally, even the called thread invoking ExitThread is not required explicitly by you, and though you can do so, I strongly advise against it in C++ programs. It is called for you once the thread procedure logically returns from the ThreadProc. I prefer the model above simply because it is dead-easy to implement and supports full RAII of C++ object cleanup, which neither ExitThread nor TerminateThread provide. For example, the ExitThread documentation :
...in C++ code, the thread is exited before any destructors can be called
or any other automatic cleanup can be performed. Therefore, in C++
code, you should return from your thread function.
Anyway, start simple. Get a handle on things with super-simple examples, then work your way up from there. There are a ton of multi-threaded examples on the web, Learn from the good ones and challenge yourself to identify the bad ones.
Best of luck.
So you need to figure out what sort of behaviour you need to have.
Following is a simple description of the methods taken from documentation:
"TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:
If the target thread owns a critical section, the critical section will not be released.
If the target thread is allocating memory from the heap, the heap lock will not be released.
If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL."
So if you need your thread to terminate at any cost, call this method.
About ExitThread, this is more graceful. By calling ExitThread, you're telling to windows you're done with that calling thread, so the rest of the code isn't going to get called. It's a bit like calling exit(0).
"ExitThread is the preferred method of exiting a thread. When this function is called (either explicitly or by returning from a thread procedure), the current thread's stack is deallocated, all pending I/O initiated by the thread is canceled, and the thread terminates. If the thread is the last thread in the process when this function is called, the thread's process is also terminated."
I have code like the following...
HANDLE event = CreateEvent(NULL, false, false, NULL);
// pass event to thread which will SetEvent(event);
DWORD dwResult = MsgWaitForMultipleObjectsEx(1, &event, 3 * 1000, QS_ALLEVENTS, 0);
Is it even possible for MsgWaitForMultipleObjectsEx to return WAIT_ABANDONED_0 in this scenario?
What types of objects can be "abandoned"?
It is described in the MSDN docs for WaitForSingleObject().
Only a mutex can cause this error condition. It indicates that the thread that acquired the mutex terminated without explicitly releasing it by calling ReleaseMutex(). That's a pretty gross error condition, something is fairly majorly borked and you should hit the Big Red Emergency Stop button when this happens. It is almost never just the mutex that's in a bad state, whatever other shared program state was touched by that thread is highly likely to be inconsistent as well.
I'm writing a multithread plugin based application. I will not be the plugins author. So I would wish to avoid that the main application crashes cause of a segmentation fault in a plugin. Is it possible? Or the crash in the plugin definitely compromise also the main application status?
I wrote a sketch program using qt cause my "real" application is strongly based on qt library. Like you can see I forced the thread to crash calling the trimmed function on a not-allocated QString. The signal handler is correctly called but after the thread is forced to quit also the main application crashes. Did I do something wrong? or like I said before what I'm trying to do is not achievable?
Please note that in this simplified version of the program I avoided to use plugins but only thread. Introducing plugins will add a new critical level, I suppose. I want to go on step by step. And, overall, I want to understand if my target is feasible. Thanks a lot for any kind of help or suggestions everyone will try to give me.
#include <QString>
#include <QThread>
#include<csignal>
#include <QtGlobal>
#include <QtCore/QCoreApplication>
class MyThread : public QThread
{
public:
static void sigHand(int sig)
{
qDebug("Thread crashed");
QThread* th = QThread::currentThread();
th->exit(1);
}
MyThread(QObject * parent = 0)
:QThread(parent)
{
signal(SIGSEGV,sigHand);
}
~MyThread()
{
signal(SIGSEGV,SIG_DFL);
qDebug("Deleted thread, restored default signal handler");
}
void run()
{
QString* s;
s->trimmed();
qDebug("Should not reach this point");
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyThread th(&a);
th.run();
while (th.isRunning());
qDebug("Thread died but main application still on");
return a.exec();
}
I'm currently working on the same issue and found this question via google.
There are several reasons your source is not working:
There is no new thread. The thread is only created, if you call QThread::start. Instead you call MyThread::run, which executes the run method in the main thread.
You call QThread::exit to stop the thread, which is not supposed to directly stop a thread, but sends a (qt) signal to the thread event loop, requesting it to stop. Since there is neither a thread nor an event loop, the function has no effect. Even if you had called QThread::start, it would not work, since writing a run method does not create a qt event loop. To be able to use exit with any QThread, you would need to call QThread::exec first.
However, QThread::exit is the wrong method anyways. To prevent the SIGSEGV, the thread must be called immediately, not after receiving the (qt) signal in its event loop. So although generally frowned upon, in this case QThread::terminate has to be called
But it is generally said to be unsafe to call complex functions like QThread::currentThread, QThread::exit or QThread::terminate from signal handlers, so you should never call them there
Since the thread is still running after the signal handler (and I'm not sure even QThread::terminate would kill it fast enough), the signal handler exits to where it was called from, so it reexecutes the instruction causing the SIGSEGV, and the next SIGSEGV occurs.
Therefore I have used a different approach, the signal handler changes the register containing the instruction address to another function, which will then be run, after the signal handler exits, instead the crashing instruction. Like:
void signalHandler(int type, siginfo_t * si, void* ccontext){
(static_cast<ucontext_t*>(ccontext))->Eip = &recoverFromCrash;
}
struct sigaction sa;
memset(&sa, 0, sizeof(sa)); sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = &signalHandler;
sigaction(SIGSEGV, &sa, 0);
The recoverFromCrash function is then normally called in the thread causing the SIGSEGV. Since the signal handler is called for all SIGSEGV, from all threads, the function has to check which thread it is running in.
However, I did not consider it safe to simply kill the thread, since there might be other stuff, depending on a running thread. So instead of killing it, I let it run in an endless loop (calling sleep to avoid wasting CPU time). Then, when the program is closed, it sets a global variabel, and the thread is terminated. (notice that the recover function must never return, since otherwise the execution will return to the function which caused the SIGSEGV)
Called from the mainthread on the other hand, it starts a new event loop, to let the program running.
if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
//sub thread
QThread* t = QThread::currentThread();
while (programIsRunning) ThreadBreaker::sleep(1);
ThreadBreaker::forceTerminate();
} else {
//main thread
while (programIsRunning) {
QApplication::processEvents(QEventLoop::AllEvents);
ThreadBreaker::msleep(1);
}
exit(0);
}
ThreadBreaker is a trivial wrapper class around QThread, since msleep, sleep and setTerminationEnabled (which has to be called before terminate) of QThread are protected and could not be called from the recover function.
But this is only the basic picture. There are a lot of other things to worry about: Catching SIGFPE, Catching stack overflows (check the address of the SIGSEGV, run the signal handler in an alternate stack), have a bunch of defines for platform independence (64 bit, arm, mac), show debug messages (try to get a stack trace, wonder why calling gdb for it crashes the X server, wonder why calling glibc backtrace for it crashes the program)...
What is the correct way to terminate a worker thread if it is taking too long to complete? I've read several articles claming that TerminateThread should be used with extreme caution, but I can't find any viable alternative.
Psudo code:
void CMyDialog::RunThread()
{
CWinThread* pThread; // pointer to thread
DWORD dwWaitResult; // result of waiting for thread
// start thread
pThread = AfxBeginThread(beginThread, this,
THREAD_PRIORITY_NORMAL,
0,
CREATE_SUSPENDED);
pThread->m_bAutoDelete = FALSE;
pThread->ResumeThread();
// wait for thread to return
dwWaitResult = ::WaitForSingleObject(pThread->m_hThread, (30 * 1000));
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
delete pThread;
// success, continue
break;
case WAIT_TIMEOUT:
// thread taking too long, terminate it
TerminateThread(pThread->m_hThread, 0);
delete pThread;
break;
} // end switch on wait result
}
UINT CMyDialog::beginThread(LPVOID pParam)
{
// convert parameter back to dialog object and call method
CMyDialog* dlg = (CMyDialog*) pParam;
dlg->readDuration();
return 0;
} // end beginThread
void CMyDialog::readDuration()
{
// call a dll function that may take longer than we are prepared to wait,
// or even hang
} // end readDuration
Is this acceptable? All comments and suggestions gratefully recieved.
I am using MFC/C++ in Visual Studio 2008. Developing on Vista, targeting XP, Vista and 7.
Is unsafe to terminate a thread, as Sanja already mentioned. The typical solution in such cases is to spawn a child process that only role is to host the DLL and call the method(s). You main process will communicate with the child process via some LPC mechanism to pass in the arguments for the DLL method invocation and get back the result. On timeout is perfectly safe to kill the child process, the kernel will reclaim all resources and there will be no in-memory or system object leaks (there could be persisted on-disk leaks, like files left over, though). It is significantly more complicated that just simply calling the DLL (you'll need to come up with the inter-process communication solution) but is the only reliable way.
Its a bad idea to use TerminateThread its not safe and can cause some leaks. You can use events to tell your thread end.
Some useful links
http://www.codeproject.com/KB/threads/Synchronization.aspx
http://msdn.microsoft.com/en-us/library/ms686915(v=vs.85).aspx
Good answer about terminatethread here