DeleteTimerQueue Not Working - c++

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?

Related

how to handle code that never executes

I have some code that looks like this and I'm unsure how to handle the part which will never get executed since a part of this code runs in infinite loop while waiting for connections and when I terminate the program, it exits from there only.
main(){
// do some stuff....
while(1) {
int newFD =
accept(sockFD, (struct sockaddr *)&client_addr, &client_addr_size);
if(newFD == -1) {
std::cerr << "Error while Accepting on socket" << std::endl;
continue;
}
if(!fork()) {
close(sockFD); // close child's sockfd - not needed here
// lalala do stuff send message here
close(newFD); // finally close its newFD - message sent, no use
return 0;
}
close(newFD); // close parent's newFD - no use here
}
// now execution never reaches here
close(sockFD); // so how to handle this?
freeaddrinfo(res); // and this?
return 0;
}
You can, and probably should add a exit handler if your code is to be used by other people or you yourself just want it cleaner. In your exit handler you can toggle a flag that makes the while() loop terminate. The following code will work 100% fine for this use case and is reliable and cross platform, but if you want to do more complicated things you should use proper thread safe OS specific functions or something like Boost or C++11
First declare two global variables, make them volatile so the compiler will always force us to read or write its actually memory value. If you we do not declare it volatile then it is possible the compiler can put its value in a register which will make this not work. With volatile set it will read the memory location on every loop and work correctly, even with multiple threads.
volatile bool bRunning=true;
volatile bool bFinished=false;
and instead of your while(1) {} loop, change it to this
while(bRunning)
{
dostuff
}
bFinished=true;
In your exit handler simply set bRunning=false;
void ExitHandler()
{
bRunning=false;
while(bFinished==false) { Sleep(1); }
}
You didn't specify an operating system but it looks like you are Linux based, to set a handler on Linux you need this.
void ExitHandler(int s)
{
bRunning=false;
}
int main()
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = ExitHandler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
while(bRunning)
{
dostuff
}
...error_handling...
}
And on Windows when you are a console app its the following.
BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
switch (CEvent)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
bRunning = false;
while (bFinished == false) Sleep(1);
break;
}
return TRUE;
}
int main()
{
SetConsoleCtrlHandler(ConsoleHandler, TRUE);
while(bRunning()
{
dostuff
}
...error_handling...
}
Notice the need to test and wait for bFinished here. If you don't do this on Windows your app may not have enough time to shutdown as the exit handler is called by a separate OS specific thread. On Linux this is not necessary and you need to exit from your handler for your main thread to continue.
Another thing to note is by default Windows only gives you ~5 seconds to shut down before it terminates you. This is unfortunate in many cases and if more time is needed you will need to change the registry setting (bad idea) or implement a service which has better hooks into such things. For your simple case it will be fine.
For these things, the OS will take care of properly releasing the resources on shutdown. However, more generally, you still need to make sure that allocated resources don't pile up during program execution, even if they are reclaimed by the OS automatically, because such a resource leak will still influence behaviour and performance of your program.
Now, concerning the resources at hand, there's no reason not to treat them like all resources in C++. The accepted rule is to bind them to an object that will release them in their destructor, see also the RAII idiom. That way, even if at some later stage someone added a break statement the code would still behave correctly.
BTW: The more serious problem I see here is the lack of proper error handling in general.

Thread is not working properly

I have a class Machine with some member function. In the makeProduct I make a thread that calls t_make and then returns. While the thread is doing it's work in the member function I still want to use Machine(status check, resource left, etc.)
I started like this
//machine.h
private
int stat;
std::thread t;
std::mutex m;
bool working;
//machine.cpp
int Machine::makeProduct(){
if(working == true) return -1;
t = std::thread(&Machine::t_make, this);
return 0;
}
void Machine::t_make(){
std::lock_guard<std::mutex> guard(m);
//do some time-consuming work, change "stat" in progress
}
void Machine::Status(int &copStat){
copStat = stat;
}
Machine::~Machine(){ if(t.joinable()) t.join; }
//main.cpp
...
Machine m;
m.makeProduct();
int getStat = 0;
m.Status(getStat);
if(getStat == 1) cout<< "Product in making";
...
The problem is that when I call makeProduct() and right after that Status() the copStat doesn't change, indicate that any work was done.
Am I using the t or t_make wrong? I tried posting lock_guard in every method but the threads don't intertwine. Or maybe the t.join() at the wrong time, but let me just mention that if I place 't.join' right after using t = std::thread(&Machine::t_make, this); and everything work out fine.
When you call Status() right after you call getProduct(), there's a good chance that the new thread hasn't started doing anything yet. You are still in the original thread, and the new thread has to set up and start running.
Your join in the destructor is not really meaningful for this exercise. If you wanted to make sure to collect the result and do something with it as Machine goes out of scope it may make sense, but it isn't meaningful to your question about checking Status. If you want Status() to only return you the value after t_make() is finished, then moving your join() code to Status would work.
Look at the Futures in the standing threading library http://en.cppreference.com/w/cpp/thread#Futures. These are utilities for executing asynchronous tasks and getting the result when the task is complete.
If t_make is modifying 'stat', then your Status function should acquire the lock before using 'stat' in the assignment of the copStat. The memory access is currently unsafe.
As the code stand right now, if you're expecting the t_make call to be complete before calling Status, there is nothing forcing this to happen. As is, two separate threads will be autonomously completing these actions - 1 thread calling t_make and 1 thread calling Status. There is no guarantee as to what order this happens in. (this changes if you add a lock to Status)
Also, could you update your example to show how you're determing that copStat is never populated?

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.

TerminateThread locks up when thread has infinate loop

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

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?