TerminateThread locks up when thread has infinate loop - c++

So I have been learning about threads in the Windows API, and I wrote some test code, but I am have some issues. First off I have two functions:
DWORD WINAPI MyThreadFunction( LPVOID lpParam )
{
int i = (int)lpParam;
cout << i << ".) I work! " << endl;
return 0;
}
And
// MyThreadFunction2 - loops continuously forever, outputing "working..." every 1ms
DWORD WINAPI MyThreadFunction2( LPVOID lpParam )
{
int i = (int)lpParam;
while(1) {
cout << i << ".) Working... " << endl;
Sleep(1);
}
return 0;
}
And I am creating threads using CreateThread, but I will change that later to _beginThread which is what people have told me to do in a different but related post. So this is how I have been creating threads:
threads.push_back(CreateThread(
NULL, // default security attributes
0, // use default stack size
lpStartAddress, // thread function name
lpParameter, // arugument to thread function
0, // use default creation flag
NULL)); // ignore thread identifier.
I am putting the thread HANDLEs I create into a vector, but that is irrelevant. Basically I have the above code working, and it creates the threads fine. The problem I am having is calling TerminateThread(HANDLE, 0) when the thread was created using MyThreadFunction2, where it loops forever. When I call TerminateThread, my program just freezes and sits there. It appears the thread has stopped, because I don't get the "Working..." message, but it doesn't continue any other code. However, when I call this same function when it is with MyThreadFunction, it works fine.
I don't know if this is extremely confusing how I am explaining what is going on, I hope it isn't. I know this isn't a place to "just dump code, and have people fix it" - I read that on someone else's post, but just incase you didn't understand a thing I wrote above, or it is helpful, here is my code:
ThreadManager.cpp
http://pastebin.com/0B1N3TAH
ThreadManager.h
http://pastebin.com/yfwMJTaz
Sorry the code is poorly written, and some things aren't complete. I am still working on re-learning C++ and learning how to use the Windows API. But does anyone have any ideas of what I might possibly be doing wrong?

Using TerminateThread to kill a thread is generally a really bad idea. Even MSDN page for this function tells you that. A better way to tell the threads to stop working is to pass them an event. With an event the thread that runs an infinite loop would do while (WaitForSingleObject(event, 1) == WAIT_TIMEOUT) instead of while (1).
Why exactly TerminateThread does what it dies, I don't know, but you can get an idea of what might be wrong when you read this http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx

Related

WINAPI CreateThread not always running thread

I am trying to create and execute a thread using Windows CreateThread API. am seeing that running the program gives non-deterministic behavior. I am seeing from the output of the program that sometimes the thread method "my" gets executed and sometimes not. What might be the reason for this? The program is very simple as shown below. Also what should dwThreadID be initialized with. Should it be 0 or any integer value?
PS:Compiling in Visual Studio.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
// DWORD WINAPI
DWORD WINAPI my (LPVOID lpParam ) {
for (int i = 0; i < 5;i++){
cout << "I am ";
}
return 0;
}
int main()
{
DWORD dwThreadID = 0;
DWORD dwThrdParam = 0;
HANDLE h = NULL;
h = CreateThread(
NULL, // default security
0, // default stack size
my, // name of the thread function
0, // no thread parameters
0, // default startup flags
&dwThreadID);
if (h == NULL){
cout <<"It is null";
}
cout << " BBBB" << endl ;
CloseHandle(h);
cout << "BBBB ";
return 0;
}
I am seeing from the output of the program that sometimes the thread
method "my" gets executed and sometimes not. What might be the reason
for this?
Probably your main thread exits before your second thread is even executed. Place breakpoint after call to CreateThread.
Or even more cleaner wait, just wait for second thread using WaitForSingleObject.
This effectively make your main thread waiting until "my" thread is done.
If CreateThread fails for some reason, you can call GetLastError right after CreateThread, it will give you ultimate answer.
Also what should dwThreadID be initialized with.
Quick look into MSDN yields following:
A pointer to a variable that receives the thread identifier.
It is indeterminate whether or not your thread executes. The main thread creates it and then terminates the program. The following may happen:
The thread may execute before the main thread terminates.
The program may terminate before the thread executes.
The thread may partially execute and be terminated when the program terminates.
You would need to add synchronization in order to be sure that the thread reaches completion. Pass the thread handle to WaitForSingleObject.
Your program does not check for errors. CreateThread returns NULL when it fails. If that happens, and only if that happens, call GetLastError for information as to why the function failed. If you add a call to WaitForSingleObject then you should check its return value for errors as described by the documentation.
What should dwThreadID be initialized with?
It does not need to be initialized because CreateThread guarantees it will be assigned if CreateThread succeeds.
Firstly do not use CreateThread it is intended for library providers. Use beginthreadex or std::thread
The likely behavior, is that the thread always runs, but it's output is being overwritten. This is because there is no synchronisation.
Check the return code and GetLastError
The value of dwThreadid does not matter

DeleteTimerQueue Not Working

I can't seem to tell why I can't stop the timer I have created using DeleteTimerQueue or any vesrion of it, such as DeleteTimerQueueTimer or Ex. Of course I fill in the arguments as needed.
At first I wanted to stop/delete the timer at a certain condition, but I have since removed that condition(an if loop) to see if Delete is working and it is not.
I am calling the Delete within the callback and I have two timers I want to stop at the same time the moment one of them accomplishes a task (that if Loop I'm talking about).
Anyway here is how I create the timers
BOOL champ1_Success = ::CreateTimerQueueTimer(
&baseAttackTimerHandler,
NULL,
callBaseAttackC1,
this,
0,
(DWORD)(1000/attackSpeed),
WT_EXECUTEDEFAULT);
BOOL champ2_Success = ::CreateTimerQueueTimer(
&baseAttackTimerHandler,
NULL,
callBaseAttackC2,
this,
0,
(DWORD)(1000/attackSpeed),
WT_EXECUTEDEFAULT);
They work great! If only I could stop them.
Within their callbacks I call
void CALLBACK Controller::callBaseAttackC1(void* lpParametar,
BOOLEAN TimerOrWaitFired)
{
// This is used only to call QueueTimerHandler
// Typically, this function is static member of CTimersDlg
Controller* obj = (Controller*) lpParametar;
if (!obj->yi->isAlive() && !obj->skarner->isAlive()){
if (!DeleteTimerQueueTimer(baseAttackTimerHandler, NULL, NULL)){
printf("Base Attack Timer failed (%d)\n", GetLastError());
obj->out << "Base A Timer Failed " << GetLastError() << endl;
}
//CloseHandle(baseAttackTimerHandler);
}
obj->basicAttackC1_TimeHandler();
}
Note the
if (!DeleteTimerQueueTimer(baseAttackTimerHandler, NULL, NULL)){
printf("Base Attack Timer failed (%d)\n", GetLastError());
obj->out << "Base A Timer Failed " << GetLastError() << endl;
}
I figure that calling the Delete within the callback would mean the timer only executes once, but it is not. It just keeps going. Another thing to note, and I'm not sure whether its good , bad or what it means but I'm have both different timers using the same Pointer to a handle, HANDL object I've created (HANDLE baseAttackTimerHandler = NULL;). I've tried making them of their own unique but it made no difference so I opted to have them use the same. BTW, DeleteTimerQueue Keeps failing when called. Error Code 87?
Bottom line is I really need them to stop, any idea what I am doing wrong or tricks to get them too?
EDIT: So I got it to work like this...
if (!DeleteTimerQueueTimer(NULL, baseAttackTimerHandler_C1, NULL)){
printf("2-Base Attack Timer failed (%d)\n", GetLastError());
obj->out << "2-Base A Timer Failed " << GetLastError() << endl;
}
but I had to make different handles for each timer to prevent error. (C1 and C2). Even though it puts out an error the first time, it stops after one execution.
However, putting it under my if loop prevents it from working. Going to have to look into my if loop.
EDIT:
Figured out what was wrong with my if loop. Since the callback seems to have to create an object of the class its in (Controller), its different than the one I initialized and am working with. So even though I do stuff with Controller con I make a Controller obj. Results in obj not the same as con and my if loop never results in true. Going to have to figure this one out. If there were a way to make the callback not be static and still use it in CreateTimer I could call con.
EDIT: Just used a strcut to make an object to set the obj equal to con indirectly. Works. I'm almost done, The timer stops but now my pop up message keeps getting spammed. I think I'm done with this thread though.
Yes, you have to use a different handle for each timer. Your original code has:
CreateTimerQueueTimer(&baseAttackTimerHandler ...);
CreateTimerQueueTimer(&baseAttackTimerHandler ...);
The second call was overwriting the handle from the first call. So when you called DeleteTimerQueueTimer to delete the timer, the handle you passed would delete the second timer but not the first.
Your solution is correct: use a different variable to hold each timer handle. That shouldn't be surprising. How can you expect to store two different handles in a single handle value?

Thread is not getting Destroyed

I am working on a Multithreaded system here's my code
class demo is defined in .h file
when the loop from the main function is executed second time the COMMENT1 below takes the previous value
doesn't closing handle closes the thread?
int threadentry(void* data)
{
demo* inst=(demo*) data;
cout << "Value of inst "<<hex << &inst<< endl;
string request;
cin>>request;
if(request==play)
{
inst->play;
cout << "Value of inst "<<hex << &inst<< endl;
// COMMENT1 here when the thread is executed second time from the main it is taking previous value
}
}
int main()
{
while(1)
{
demo* inst=new demo();
cout << "Value of inst "<<hex << &inst<< endl; //value is coming different from above
HANDLE threads;
DWORD threadId1;
if ((threads = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadentry,
(void *)inst, 0, &threadId1)) == NULL)
return -1;
//here is some Processing of data and after processing I close the handle
CloseHandle(threads);
delete inst;
system("pause");
}
}
No -- closing a handle to a thread does not destroy the thread itself. The thread should exit (either by calling ExitThread or by just returning from the thread function) when it's finished doing its job.
In emergencies, you can use TerminateThread to kill a thread, but that should be reserved for true emergencies -- it can leave the process in an unstable state, so it should generally be avoided, and if you have to use it, you probably want to shut down the process as soon afterwards as possible.
Also note that in a program that uses the standard library, it's not really safe to use CreateThread directly -- you should call _beginthread or _beginthreadex instead. These do some setup to allow thread-safe use of standard library functions that use static storage (e.g., strtok and mktime, but there are quite a few more).
Drop all those "(type)foo" casts, they are forcing the compiler to accept things that in reality don't fit. You will have to fix a few errors there by replacing things with the proper type. For the context pointer passed to the thread, the conversion from demo* to void* is implicit. The correct cast to reverse this is static_cast<demo*>(data). If you want, you can use the a static cast for the implicit conversion, too. There are missing return values in functions, too, the only case that is allowed is in main(). The reason I mention th s is that formally, anything can happen in your program, because these things cause undefined behaviour.
Then, you are outputting the "value of inst" but actually outputting the address of local variables called "inst", which is something different. This probably just adds to your confusion.
Now, coming to your problem, CloseHandle() does not stop the thread. It only releases your handle. What you want is WaitForSingleObject() or one of its brethren instead.

Segfault accessing classes across threads

I'm a bit stumped on an issue I'm having with threading and C++. I'm writing a DSP plugin for Windows Media Player, and I want to send the data I intercept to a separate thread where I'll send it out on the network. I'm using a simple producer-consumer queue like the one explained here
The program is crashing on the isFull() function which just compares two integers:
bool ThreadSafeQueue::isFull()
{
if (inCount == outCount) //CRASH!
return true;
else
return false;
}
The thread that's doing the dequeuing:
void WMPPlugin::NetworkThread (LPVOID pParam)
{
ThreadSafeQueue* dataQueue = (ThreadSafeQueue*)(pParam);
while (!networkThreadDone)
{
Sleep(2); /// so we don't hog the processor or make a race condition
if (!dataQueue->isFull())
short s = dataQueue->dequeue();
if (networkThreadDone) // variable set in another process so we know to exit
break;
}
}
The constructor of the class that's creating the consumer thread:
WMPPlugin::WMPPlugin()
{
// etc etc
dataQueue = new ThreadSafeQueue();
_beginthread(WMPPlugin::NetworkThread, 0, dataQueue);
}
inCount and outCount are just integers and they're only read here, not written. I was under the impression this meant they were thread safe. The part that writes them aren't included, but each variable is only written to by one thread, never by both. I've done my best to not include code that I don't feel is the issue, but I can include more if necessary. Thanks in advance for any help.
Most often, when a crash happens accessing a normal member variable, it means this is NULL or an invalid address.
Are you sure you aren't invoking it on a NULL instance?
Regarding this line:
ThreadSafeQueue* dataQueue = (ThreadSafeQueue*)(pParam);
How sure are you that pParam is always non-NULL?
How sure are you that pParam is always a ThreadSafeQueue object?
Are you possible deleting the ThreadSafeQueue objects on other threads?

PThread Question

I am trying to make a small thread example. I want to have a variable and each thread try to increment it and then stop once it gets to a certain point. Whenever the variable is locked, I want some sort of message to be printed out like "thread x trying to lock, but cannot" so that I KNOW it's working correctly. This is my first day coding threads so feel free to point out anything unnecessary in the code here -
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define NUM_THREADS 2
pthread_t threads[NUM_THREADS];
pthread_mutex_t mutexsum;
int NUMBER = 0;
void* increaseByHundred(void* threadid) {
if(pthread_mutex_lock(&mutexsum))
cout<<"\nTHREAD "<<(int)threadid<<" TRYING TO LOCK BUT CANNOT";
else {
for(int i=0;i<100;i++) {
NUMBER++;
cout<<"\nNUMBER: "<<NUMBER;
}
pthread_mutex_unlock(&mutexsum);
pthread_exit((void*)0);
}
}
int main(int argc, char** argv) {
int rc;
int rc1;
void* status;
pthread_attr_t attr;
pthread_mutex_init(&mutexsum, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
rc = pthread_create(&threads[0], &attr, increaseByHundred, (void*)0);
rc1 = pthread_create(&threads[1], &attr, increaseByHundred, (void*)1);
pthread_attr_destroy(&attr);
while(NUMBER < 400)
pthread_join(threads[0], &status);
pthread_mutex_destroy(&mutexsum);
pthread_exit(NULL);
}
I was following a tutorial found here https://computing.llnl.gov/tutorials...reatingThreads
and tried to adapt their mutex example to this idea. The code increments it up to 199 and then stops. I'm guessing because the threads are only doing their routine once. Is there a way make them just do their routine other than when you create them so I could say
while something
do your routine
?
I have the pthread_join there just because it was similar to what that tutorial had on theirs. I don't really even get it that clearly though. I'm pretty sure that line is the problem...I just don't know how to fix it. Any help is appreciated.
Whenever the variable is locked, I want some sort of message to be printed out like "thread x trying to lock, but cannot" so that I KNOW it's working correctly.
Why do you want that? You are just learning about threads. Learn the basics first. Don't go diving off the deep end into pthread_mutex_trylock or mutexes configured for error checking. You need to learn to walk before you can learn how to run.
The basics involves a mutex initialized use with default settings and using pthread_mutex_lock to grab the lock. With the default settings, pthread_mutex_lock will only return non-zero if there are big, big problems. There are only two problems that can occur here: Deadlock, and a bad mutex pointer. There is no recovery from either; the only real solution is to fix the code. About the only thing you can do here is to throw an exception that you don't catch, call exit() or abort(), etc.
That some other thread has locked the mutex is not a big problem. It is not a problem at all. pthread_mutex_lock will block (e.g., go to sleep) until the lock becomes available. A zero return from pthread_mutex_lock means that the calling thread now has the lock. Just make sure you release the lock when you are done working with the protected memory.
Edit
Here's a suggestion that will let you see that the threading mechanism is working as advertised.
Upon entry to increaseByHundred print a time-stamped message indicating entry to the function. You probably want to use C printf here rather than C++ I/O. printf() and related functions are thread-safe. C++ 2003 I/O is not.
After a successful return from pthread_mutex_lock print another time-stamped message indicating that a successful lock.
sleep() for a few seconds and then print yet another time-stamped message prior to calling pthread_mutex_unlock().
Do the same before calling pthread_exit().
One last comment: You are checking for an error return from pthread_mutex_lock. For completeness, and because every good programmer is paranoid as all get out, you should also check the return status from pthread_mutex_unlock.
What about pthread_exit? It doesn't have a return status. You could print some message after calling pthread_exit, but you will only reach that statement if you are using a non-compliant version of the threads library. The function pthread_exit() cannot return to the calling function. Period. Worrying about what happens when pthreads_exit() returns is a tinfoil hat exercise. While good programmers should be paranoid beyond all get out, they should not be paranoid schizophrenic.
pthread_mutex_lock will normally just block until it acquire the lock, and that's why the line cout<<"\nTHREAD "<<(int)threadid<<" TRYING TO LOCK BUT CANNOT"; is not ran.
You also have problems in
while(NUMBER < 400)
pthread_join(threads[0], &status);
because you just have 2 threads and number will never reach 400. You also want to join thread[0] on first iteration, then thread[1]...
pthread_mutex_trylock():
if (pthread_mutex_trylock(&mutex) == EBUSY) {
cout << "OMG NO WAY ITS LOCKED" << endl;
}
It is also worth noting that if the mutex is not locked, it will be able to acquire the lock and then it will behave like a regular pthread_mutex_lock().