Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic Operation 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.

like image 623
akif Avatar asked Dec 02 '22 07:12

akif


1 Answers

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()
like image 167
shoosh Avatar answered Dec 24 '22 19:12

shoosh