Atomic Operation C++ - c++

In C++, Windows platform, I want to execute a set of function calls as atomic so that execution doesn't switches to other threads in my process. How do I go about doing that? Any ideas, hints?
EDIT: I have a piece of code like:
someObject->Restart();
WaitForSingleObject(handle, INFINITE);
Now the Restart() function does its work asynchronously, so it returns quickly and when that someObject is restarted it sends me an event from another thread where I signal the event handle on which I'm waiting and thus continue processing. But now the problem is that before the code reaches WaitForSingleObject() part, I receive the restart completion event and I signal the event and after that WaitForSingleObject() never returns since it is not signaled again. That's why I want to execute both Restart() and WaitForSingleObject() as atomic.

This is generally not possible. You can't force the OS to not switch to other threads.
What you can do is one of the following:
Use locks, mutexes, criticals sections or semaphores to synchronize a handful of threads that touch the same data.
Use basic operations that are atomic such as compare-and-exchange or atomic-add in the form of win32 api calls such as InterlockedIncrement() and InterlockedCompareExchange()

You don't want all threads to wait, you just want to wait for the new thread to be done, without the risk of missing the signal. This can be done using a semaphore.
Create a semaphore known by both this code and the code eventually executed by Restart, using CreateSemaphore(NULL,0,1,NULL).
In the code you've shown, you'll still use WaitforSingleObject to wait for your semaphore. When the thread executing the Release code is done with it's work, have it call ReleaseSemaphore.
If ReleaseSemaphore is called first, WaitforSingleObject will let you pass immediately. If WaitforSingleObject is called first, it will wait for ReleaseSemaphore.
MSDN should also help you.

A general solution to lost event race is a counting semaphore.

Are you using PulseEvent() to signal your handle? If so, that's the problem.
According to MSDN,
If no threads are waiting, or if no
thread can be released immediately,
PulseEvent simply sets the event
object's state to nonsignaled and
returns.
So if the handle is signaled before you wait on it, the handle is placed immediately in the nonsignaled state by PulseEvent(). That would appear to be why your are "missing" the event. To correct this, replace PulseEvent() with SetEvent().
With this scenario, though, you may need to reset the event after the wait is complete. This of course depends on if this code is executed more than once during the lifetime of your application. Assuming your waiting thread is the only thread that is waiting on the handle, use CreateEvent() to create an auto reset event. This will automatically reset the handle after your waiting thread is released, making it automatically available for the next time through.

Well, you could suspend (using SuspendThread) all other threads in the process, but I suppose you should rethink design of your program.

This is very easy to fix. Just make sure that the event is the auto-reset event (see the parameters of the CreateEvent) and only call SetEvent to the event handle, never call ResetEvent or PulseEvent or some other things. So the WaitForSingleObject will always return properly. If the event has been already set, the WaitForSingleObject will return immediately and reset the event.

Although I worry about your design in general (ie you are making concurrent tasks sequential, thus losing all the benefits of the hard work to make it concurrent), I think I see the simple solution.
Change your event handle to be MANUAL RESET instead of AUTORESET. (see CreateEvent).
Then you won't miss the signal.
After WaitForSingleObject(...), call ResetEvent().
EDIT:
forget what I just said. That won't work. see comments below.

Related

How do I execute a C++ function asynchronously and not block/wait?

I want to execute a function asynchronously and not wait for it to complete. I initially thought I could use std::async with launch::async, but the returned future's destructor blocks until the function is complete.
Is there a way of running a function on a thread pool using stl without blocking?
You should spawn a single new thread which waits on a counting semaphore. When it is awoken (unblocked), it will send one RPC request and decrement the counter. When the user clicks the button, increment the counter. The same thread can service all requests throughout the program's lifetime.
You're looking for std::thread::detach. http://en.cppreference.com/w/cpp/thread/thread/detach
You can create a thread, and then detach from it. At that point you can delete your thread handle and the thread will run without you.
Incidentally it's usually considered bad form to use this technique. Generally you should care about the state of the thread, and should try to shut it down gracefully at program end, but in practice this is a useful trick for when you really don't care.
This proposal talks about executors... it looks like the kind of thing I was hoping I'd find existed already, but it looks like it doesn't.
http://isocpp.org/files/papers/n4039.html

How to end _beginthreadex()?

Inside my desktop application I have created a simple thread by using _beginthreadex(...). I wonder what happens if my application will be closed (without explicitly closing the thread)? Will all resources inside the thread be cleared automatically? I have doubts.
So I like to end the thread when my application will be closed. I wonder what would be the best practise?
Using _endthreadex is only possible inside(!) the thread and something like TerminateThread(...) does not seems to work (infinite loop). Do you have some advices?
When main exits your other threads will be destroyed.
It's best to have main wait on your other threads, using their handles, and send them a message (using an event, perhaps) to signal them to exit. Main can then signal the event and wait for the other threads to complete what they were doing and exit cleanly. Of course this requires that the threads check the event periodically to see if they need to exit.
When the main thread exits, the app and all of its resources are cleaned up. This will include other threads and their resources.
Also, post the code you have for TerminateThread, because it works.
The tidiest way is to send your thread(s) a message (or otherwise indicate via an event) that the tread should terminate and allow it to free its resources and exit its entry point function.
To close the thread, you need to call CloseHandle() with the handle returned by _beginthreadex.
The thread is part of the process, so when the process terminates it will take the thread with it and the operating system will resume ownership of everything the two own, so all the resources will be released.
Bear in mind that if you have not forewarned the thread that the-end-is-nigh, it may be in the middle of some work when it ends. If it is in the middle of using any system or external resources, they will be released but may be in a funky state (e.g. a file may be partially written, etc).
See also http://www.bogotobogo.com/cplusplus/multithreading_win32A.php
Note: Using CloseHandle() is only for _beginthreadex and not if you are using _beginthread. See http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.90).aspx

QT QEventLoop/QThread how to synchronize on an event loop?

I need a way to know when an event loop has started and when it is about to exit. I am trying to synchronize between threads and there is hard to resolve race condition involving isRunning at the times when the loop starts and when it exits.
I believe for starting I can simply post an event since it will be queued and dispatched once it starts. But for exiting I'm not sure how to handle it. I need some kind of event that will happen just prior to the loop completing.
Is there any way to accomplish this?
The reason I need this is for posting events to the thread. I have a function, a cleanup function in particular, say cleanupObject. This function can be called from any thread and is expected to do cleanup on the object. These objects are owned by a thread with an event loop. If this event loop is running this cleanupObject request has to be processed as an event in that event loop. If the event loop is not running then the cleanup has to be handled differently (this happens during shutdown).
The race exists because isRunning has no synchronization I can use, so while it said true when I called it, it may not longer be running the instant after. I need to know whethere the event I post to the loop will be processed or not, because if it will not be processed I must do cleanup in a different fashion.

Stopping an MFC thread

I understand the problem with just killing the thread directly (via AfxEndThread or other means), and I've seen the examples using CEvent objects to signal the thread and then having the thread clean itself up. The problem I have is that using CEvent to signal the thread seems to require a loop where you check to see if the thread is signaled at the end of the loop. The problem is, my thread doesn't loop. It just runs, and the processing could take a while (which is why I'd like to be able to stop it).
Also, if I were to just kill the thread, I realize that anything I've allocated will not have a chance to clean itself up. It seems to me like any locals I've been using that happen to have put stuff on the heap will also not be able to clean themselves up. Is this the case?
There is no secret magic knowledge here.
Just check the event object periodically throughout the function code, where you deem it is safe to exit.
Does your thread ever exit? If so, you could set an event in the thread at exit and have the main process wait for that event via waitforsingleevent. This is best to do with a timeout so the main process doesn't appear to lockup when it's closing. At the timeout event, kill the thread via AfxKillThread. You'll have to determine what a reasonable timeout is, though.
Since you don't loop in the thread this seems to me to be the only way to do this. Of course, you could something like set a boolean flag in the main process and have the thread periodically check this flag, but then your thread code will be littered with "if(!canRun) return;" type code.
If the thread never exits, then AfxKillThread/AfxTerminateThread is the only way to stop the thread.
Locals would be placed on the stack and, hence, WOULD be freed on forcing the thread shut (I think). Destructors won't get called though and any critical sections the thread holds will not get released.
If the thread is ONLY doing things with simple data types on the stack, however, it IS a safe thing to be doing.

How do i know if a thread is suspended under Windows CE

Can I get a threads suspend count under Windows CE, using C or Visual C++, without calling resume or suspend functions? The only way I can see of doing it is something like
int Count = SuspendThread(ThreadHandle);
ResumeThread(ThreadHandle);
This has a couple of problems, firstly, I'd rather not suspend the thread, and secondly the suspend might fail if the thread is running kernel code. I can work around this, but I feel there should be a more elegant solution. I could also reverse it using
int Count = ResumeThread(ThreadHandle);
SuspendThread(ThreadHandle);
But this has similar problems. Any good alternative method of getting the suspend count from the handle?
I have a combined solution. Use WaitForSingleObject() to determine if the thread is suspended or not.
If it's not suspended, the suspend count is obviously 0.
If it's suspended, it's safe to call SuspendThread() to get the suspend count. Since it's already suspended you will not stall anything.
You should not suspend any thread on any platform, ever.
You should instead add synchronization points in your threading code that explicitly waits for a flag to become signaled before it is allowed to continue. This way you know where it will be paused, or at least know that it will be paused at safe points.
The following operations on threads should be banned, outright, from any platform for any programmer:
Suspend
Resume (since you don't need it if you can't suspend the thread)
Kill/Abort
You should never, ever, forcibly impose your will from the outside on a thread. You have no guarantee what it is doing, what kind of resources it is currently locking.
Always write threading in a cooperative mode. Your thread should be aware of its surroundings, and yield to wishes of the outside world to either exit in an orderly fashion, or pause until it can safely continue.
Probably with WaitForSingleObject you can check if the thread is suspended but you can not retrieve the suspend counter.
Even the Thread in Active you will still receive a WAIT_TIMEOUT result, this because Threads only signal when they finish, not when they're running.
That said WaitForSingleObject(hThread,INFINITE) waits until the threads finishes.