WaitForSingleObject gets his semaphore in XP but not in Vista - c++

The following code runs perfectly well on my XP SP2 machine, but the call to WaitForSingleObject waits indefinitely when running on my Vista machine:
HANDLE ghSemaphore;
ghSemaphore = CreateSemaphore(NULL, 0, 1, "COM_PHILOERTEL_FINA");
if (ghSemaphore == NULL) {
MessageBoxA(NULL,"Error creating semaphore","ERROR",0);
return FALSE;
}
MessageBoxA(NULL,"Semaphore created. Waiting for it to be triggered","ERROR",0);
WaitForSingleObject(ghSemaphore, INFINITE);
// got the semaphore, ready to rock
MessageBoxA(NULL,"Got the semaphore, ready to rock!","Notice",0);
Here's the thread that releases the semaphore:
ghSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, "COM_PHILOERTEL_FINA");
if (ghSemaphore == NULL) {
MessageBoxA(NULL,"Failed to open semaphore","ERROR",0);
return FALSE;
}
if (0 == ReleaseSemaphore(ghSemaphore, 1, NULL)) {
MessageBoxA(NULL,"Plugin was unable to release the semaphore","ERROR",0);
return FALSE;
}
The named semaphore was a recent addition that didn't do any good. Before that the threads were just sharing ghSemaphore with its anonymous semaphore. No apparent difference. Does anyone have any idea why this binary (compiled on the XP machine in VC6, Express Edition fwiw) wouldn't work in Vista? As I said above, the WaitForSingleObject call is what never finishes.
THanks!

I cannot check it right now, but heard about it, so try:
Change first argument of CreateSemaphore from NULL to empty instance of SECURITY_ATTRIBUTES
SECURITY_ATTRIBUTES dumy;
dumy.nLength = sizeof(dumy);
dumy.lpSecurityDescriptor = 0;
dumy.bInheritHandle = TRUE;
CreateSemaphore(&dumy, 0, 1, "COM_PHILOERTEL_FINA");
By the way named semaphore with lMaximumCount = 1 is fully equivalent of named mutex. So review possibility to use mutex.

Solved. This was entirely user error. Thanks #Dewfy, #Naveen, and #avakar for your thoughtful responses.
I was sure the user function was being called because I was displaying its result in my Filemaker layout. What I failed to realize is that these return values are cached by default. The function was never being called. Your suggestions were really helpful, because it wasn't until I fully understood what I was doing with my threads and semaphores that I was able to step back and say "hang on, something's not right here".
I'm still grappling with the mystery of why when I removed the semaphore code I was able to access the resource that the user function was supposed to provide, even though that function was not running. But that's a separate issue.
feels GOOD

Related

Interogate which process has locked a file in Windows C ++

I have 2 applications sharing the same lock file, and I need to know when the
the other application has either locked/unlocked the file. The code below was
originally implemented on a Linux machine, and is being ported to Window 8, VS12.
I have ported all other code in the class successfully and am locking files with
LockFile(handle, 0, 0, sizeof(int), 0) and the equivalent UnlockFile(...). However,
I am having trouble with the following wait() command.
bool devices::comms::CDeviceFileLock::wait(bool locked,
int timeout)
{
// Retrieve the current pid of the process.
pid_t pid = getpid();
// Determine if we are tracking time.
bool tracking = (timeout > 0);
// Retrieve the lock information.
struct flock lock;
if (fcntl(m_iLockFile, F_GETLK, &lock) != 0)
raiseException("Failed to retrieve lock file information");
// Loop until the state changes.
time_t timeNow = time(NULL);
while ((pid == lock.l_pid)
&&
(lock.l_type != (locked ? F_WRLCK : F_UNLCK)))
{
// Retrieve the lock information.
if (fcntl(m_iLockFile, F_GETLK, &lock) != 0)
raiseException("Failed to retrieve lock file information");
// Check for timeout, if we are tracking.
if (tracking)
{
time_t timeCheck = time(NULL);
if (difftime(timeNow, timeCheck) > timeout)
return false;
}
}
// Return success.
return true;
}
Note: m_iLockFile used to be a file descriptor from open(), it is now called
m_hLockFile and is a HANDLE from CreateFile().
I cannot seem to find the Windows equivalent of the fcntl F_GETLK command.
Does anyone know if I can either:
a) use an fcntl equivalent to interrogate locking information, to find out
which process has obtained the lock
b) suggest how the above can be re-written for Windows C++.
Note: The server application using the lock file is a standalone C++ executable,
however the client using the lock file is a WinRT Windows Application. So any
suggested solution cannot break the sandboxing of the client.
Thanks.
You are not going to find this in Windows, it is fundamentally unsound on a multi-tasking operating system. The value you'd get from an IsFileLocked() api function is meaningless, another process or thread could still lock the file a microsecond later.
The workaround is simple, if you need to lock then just try to acquire one. If the file is already locked then LockFile() will simply return FALSE, GetLastError() tells you why. Now it is atomic, an essential property of a lock. If you can afford to wait for the lock then use LockFileEx() without the LOCKFILE_FAIL_IMMEDIATELY option.
I am just googling for you, but I found this
"Various C language run-time systems use the IOCTLs for purposes
unrelated to Windows Sockets. As a consequence, the ioctlsocket
function and the WSAIoctl function were defined to handle socket
functions that were performed by IOCTL and fcntl in the Berkeley
Software Distribution."
There is also a brief discussion here - it is python based but has some clues.

How to restart a multithreaded C++ program inside the code?

as i describe in the header I would like to have in a thread an if statement which is checked every 1 minute and if it is true restart the whole programm.. Any suggestions?
void* checkThread(void* arg)
{
if(statement)
//restart procedure
sleep(60);
}
int main()
{
pthread_create(&thread1, NULL, checkThread, main_object);
pthread_create();
pthread_create();
}
If you are going for the nuke-it-from-orbit approach (i.e. you don't want to trust your code to do a controlled shutdown reliably), then having the kill-and-auto-relaunch mechanism inside the same process space as the other code is not a very robust approach. For example, if one of the other threads were to crash, it would take your auto-restart-thread down with it.
A more fail-safe approach would be to have your auto-restart-thread launch all of the other code in a sub-process (via fork(); calling exec() is allowable but not necessary in this case). After 60 seconds, the parent process can kill the child process it created (by calling kill() on the process ID that fork() returned) and then launch a new one.
The advantage of doing it this way is that the separating of memory spaces protects your relauncher-code from any bugs in the rest of the code, and the killing of the child process means that the OS will handle all the cleanup of memory and other resources for you, so there is less of a worry about things like memory or file-handle leaks.
If you want a "nice" way to do it, you set a flag, and then politely wait for the threads to finish, before relaunching everything.
main_thread() {
do {
kill_and_restart_everything = false;
// create your threads.
pthread_create(&thread1, NULL, checkThread, main_object);
pthread_create(&thread2, ...);
pthread_create(&thread3, ...);
// wait for your threads.
pthread_join(thread1, nullptr);
pthread_join(thread2, nullptr);
pthread_join(thread3, nullptr);
} while (kill_and_restart_everything);
}
void* checkThread(void* arg) {
while (! kill_and_restart_everything) {
if(statement)
kill_and_restart_everything = true;
else
sleep(60);
}
}
void* workerThread(void* arg) {
// do stuff. periodically check
if (kill_and_restart_everything) {
// terminate this thread early.
// do it cleanly too, release any resources, etc (RAII is your friend here).
return nullptr;
}
// do other stuff, remember to have that check happen fairly regularly.
}
This way, whenever if(statement) is true, it will set a boolean that can be used to tell each thread to shut down. Then the program waits for each thread to finish, and then starts it all over again.
Downsides: If you're using any global state, that data will not be cleaned up and can cause problems for you. If a thread doesn't check your signal, you could be waiting a looooong time.
If you want to kill everything (nuke it from orbit) and restart, you could simply wrap this program in a shell script (which can then detect whatever condition you want, kill -9 the program, and relaunch it).
Use the exec system call to restart the process from the start of the program.
you can do it in two parts:
Part1: one thread that checks for the statement and sets a boolean to true when you need to restart the program
This is the "checker" thread
Part2: one thread that computes what you want:
this will "relaunch" the program as long as needed
This "relaunch" consists in a big loop
In the loop:
creates a thread that will actually execute your programme (the task you want to be executed)
ends this taks when the boolean is set to true
creates another thread to replace then one that is terminated
The main of your program consists in launching the "checker" and the "relauncher"
Tell me if you have any questions/remarks I can detail or add some code

WaitForSingleObject times out too fast

I have this piece of code in a secondary thread:
DWORD result = WaitForSingleObject(myhandle,10000);
if(result == WAIT_OBJECT_0){
AfxMessageBox(_T(...));
}
else if(result == WAIT_TIMEOUT){
AfxMessageBox(_T("Timeout"));
}
Sometimes, not always, the timeout will get called almost as soon as the WaitForSingleObject is called (not even 1s delay).
Am I doing something wrong ? Any suggestions for more stable alternatives ?
EDIT:
myhandle is created inside a class constructor as:
myhandle = CreateEvent(NULL,FALSE,FALSE,_T("myhandle"));
it would get called by another function:
SetEvent(myhandle);
The point is it works when I do the SetEvent, the problem is that it sometimes times out as soon as the WaitForSingleObject is called, even though it should wait 10s.
Do you really need/want a named event? Typically this is only required for inter-process concurrency control.
If you have multiple instances of this class they will all use the same event - see the docs for CreateEvent about calling for a named object that already exists.
It may be that all you need to do is remove the name here. This allows each class instance to have its own Event object and behaviour should be more predictable.
WaitForSingleObject will not wait the whole 10 seconds. It will wait for the first of:
The timeout value is elapsed
The event is signaled
The handle becomes invalid (closed in another thread)
If the event is set when you call WaitForSingleObject, condition #2 is true from the start and WaitForSingleObject returns immediatly.
If you want to always wait 10 seconds, you should use code like this :
//Always wait 10 seconds
Sleep(10000);
//Test the event without waiting
if(WaitForSingleObject(myhandle, 0) == WAIT_OBJECT_0) {
AfxMessageBox(_T("Event was set in the last 10 secondes"));
} else {
AfxMessageBox(_T("Timeout"));
}
Took awhile but the problem actually was that the program sometimes did multiple calls to WaitForSingleObject. So it's a previous call that is timing out.
Solution is to use WaitForMultipleObjects and set a cancelling event in the case it is known that the first event won't be set, so the timer is cancelled before is it re-invoked.

CreateThread failure on a longterm run

I'm writing a program in C++ using WINAPI to monitor certain directory for new files arriving, and send them in certain order. The files are derived from a live video stream, so there are 2 files in a unit - audio file and video file, and units should be sent in sequence. a. k. a. (1.mp3, 1.avi); (2.mp3, 2.avi)... Architecture is:
1) detect a new file added to the folder, insert file name to the input queue
2) organize files into units, insert units into unit queue
3) send unit by unit
But since I have to use monitoring file directory for files added there, I need to make sure that file is complete, a. k. a. it is ready to send, since the signal appears when the file is created, but it has yet to be filled with info and closed. So I pop file name from a input queue either when queue has more than 1 file (a. k. a. signal came for next file created, that means that previous file is ready to send) or on timeout(10 sec) so for 10 seconds any file should be done.
So in general this program runs and works properly. But, if I assume that the send procedure will take too long time, so the unit queue will grow. And after some number of units buffered in a unit queue the bug appears.
time[END] = 0;
time[START] = clock();
HANDLE hIOMutex2= CreateMutex (NULL, FALSE, NULL);
WaitForSingleObject( hIOMutex2, INFINITE );
hTimer = CreateThread(NULL, 0, Timer, time, 0, &ThreadId1);
if(hTimer == NULL)
printf("Timer Error\n");
ReleaseMutex(hIOMutex2);
ReadDirectoryChangesW(hDir, szBuffer, sizeof(szBuffer) / sizeof(TCHAR), FALSE, FILE_NOTIFY_CHANGE_FILE_NAME, &dwBytes, NULL, NULL);
HANDLE hIOMutex= CreateMutex (NULL, FALSE, NULL);
WaitForSingleObject( hIOMutex, INFINITE );
time[END] = clock();
TerminateThread(hTimer, 0);
ReleaseMutex( hIOMutex);
After around 800 units buffered in a queue, my program gives me "Time Error" message, if I'm right that means that program can't allocate thread. But in this code program terminates timer thread exactly after the file was created in a directory. So I'm kind of confused with this bug. Also interesting is that even with this time error, my program continue to send units as usual, so that doesn't look like a OS mistake or something different, it is wrong thread declaration/termination, at least it seems like that to me.
Also providing Timer code below if it is helpful.
DWORD WINAPI Timer(LPVOID in){
clock_t* time = (clock_t*) in;
while(TRUE){
if(((clock() - time[START])/CLOCKS_PER_SEC >= 10) && (!time[END]) && (!output.empty())){
Send();
if(output.empty()){
ExitThread(0);
}
}
else if((output.empty()) || (time[END])){
break;
}
else{
Sleep(10);
}
}
ExitThread(0);
return 0;
}
Please could anyone here give me some advise how to solve this bug? Thanks in advance.
Using TerminateThread is a bad idea in many ways. In your case, it makes your program fail because it doesn't release the memory for the thread stack. Failure comes when your program has consumed all available virtual memory and CreateThread() cannot reserve enough memory for another thread. Only ever use TerminateThread while exiting a program.
You'll have to do this a smarter way. Either by asking a thread to exit nicely by signaling an event or by just not consuming such an expensive system resource only for handling a file. A simple timer and one thread can do this too.

Threading in a DLL where the DLL must return before child thread finishes

I am working on writing a wrapper DLL to interface a communication DLL for a yokogawa WT1600 power meter, to a PC based automation package. I got the communication part to work but I need to thread it so that a 50ms scan time of the automation package can be maintained. (The Extended Function Block (EFB) Call will block the scan until it returns)
These are the steps I need to do.
Call EFB
EFB creates a thread to perform communication setup (takes about 200ms to do)
EFB returns EFB_BUSY while the thread is doing the work
3a. (automation program continues scanning until it comes back to the EFB call)
Call EFB passing in that it returned busy on the last call
EFB checks if the thread has returned
If the thread returned Then the EFB returns success, Else return EFB_BUSY
repeat 3a-6 until efb returns success
So my problem is, how do I create a thread that exists past the life of the function that called it? And how do I get that thread return value when I call back into the DLL?
EDIT #1
HeavyFunction::HeavyFunction^ hf; //HeavyFunction is a class that has a time consuming function in it
ThreadStart^ efbThreadDelegate;
Thread^ efbThread;
if( pEfbData->nBlockingRecall != DOEFB_BUSY ) {
hf = gcnew HeavyFunction::HeavyFunction;
hf->iiStart = (int)(pEfbData->uParams[0].dw);
hf->iiEnd = (int)(pEfbData->uParams[1].dw);
efbThreadDelegate = gcnew ThreadStart( hf, &HeavyFunction::HeavyFunction::iGetPrime );
efbThread = gcnew Thread( efbThreadDelegate );
efbThread->Start();
return DOEFB_BUSY;
}else if ( efbThread->IsAlive ) {
return DOEFB_BUSY;
}else {
uRetValue->dw = hf->iReturn;
return 0;
}
Will efbThread still have the same thread handle upon a subsequent call?
EDIT #2
I got it to work by creating a global HANDLE for a Mutex and a thread. Initializing the mutex in the init entry point (done upon dll loading) and creating the thread in the main function when a call is actually made to the dll.
I used the sample code from MSDN: Creating Threads as my model.
Any thread created (whether in a DLL or elsewhere) will not stop spontaneously. In particular, the function that created the thread may return. The new thread would still run even if the creator thread exited. That is, assuming it didn't hit the end of its entry function.
Windows threads return a DWORD when ready. To peek, call WaitForSingleObject on the thread handle with a 0 second timeout, and it that succeeds, call GetExitCodeThread .
I don't understand your whole "EFB" thing, neither what it is nor what it does, though. If it is doing funny things to normal Windows threads, all bets are off.