thread-safe timer for C++ callback - c++

In a unix pthreads based app I'm working on, I have objects of a particular class (call it class foo) being created in multiple threads. I need a specific public method of class foo invoked at or after 60s of the object coming into existence (it is not imperative that it happens at precisely 60s, just that it happens at either 60s or very shortly thereafter).
Any ideas on what timers are available that could I use to achieve this? Looking for either something that I could just drop right in to my class foo or which I could derive from.
The only real requirement is that it be thread-safe.

There are various platform specific mechanisms which will allow you to force an interruption of a thread at a given time, depending on various platform specific preconditions relating to the state of the thread. These are a bad idea unless you really need them and know why.
The correct solution, given the information in your question, would be to simply check elapsed time. Presumably these threads do some work in some sort of loop. As part of this loop, you should call e.g. foo::tick() and then let tick check to see if 60s has elapsed.

Rather than using timer, why not define a static member within the class that is incremented in the constructor (with proper protection of course)? When the static member reaches 60, either invoke the member or flag that the condition has occurred and invoke elsewhere.

Related

How to expose a thread-safe interface that allocate resources?

I'm trying to expose a C interface for my C++ library. This notably involve functions that allow the user to create, launch, query the status, then release a background task.
The task is implemented within a C++ class, which members are protected from concurrent read/write via an std::mutex.
My issue comes when I expose a C interface for this background task. Basically I have say the following functions (assuming task_t is an opaque pointer to an actual struct containing the real task class):
task_t* mylib_task_create();
bool mylib_task_is_running(task_t* task);
void mylib_task_release(task_t* task);
My goal is to make any concurrent usage of these functions thread-safe, however I'm not sure exactly how, i.e. that if a client code thread calls mylib_task_is_running() at the same time that another thread calls mylib_task_release(), then everything's fine.
At first I thought about adding an std::mutex to the implementation of task_t, but that means the delete statement at the end of mylib_task_release() will have to happen while the mutex is not held, which means it doesn't completely solve the problem.
I also thought about using some sort of reference counting but I still end up against the same kind of issue where the actual delete might happen right after a hypothetical retain() function is called.
I feel like there should be a (relatively) simple solution to this but I can't quite put my hand on it. How can I make it so I don't have to force the client code to protect accesses to task_t?
if task_t is being deleted, you should ensure that nobody else has a pointer to it.
if one thread is deleting task_t and the other is trying to acquire it's mutex, it should be apparent that you should not have deleted the task_t.
shared_ptrs are a great help for this.

How to templatize code for a class member function based on constructor parameter

I have a highly performance-sensitive (read low latency requirement) C++ 17 class for logging that has member functions that can either log locally or can log remotely depending upon the flags with which the class is implemented. "Remote Logging" or "Local Logging" functionality is fully defined at the time when the object is constructed.
The code looks something like this
class Logger {
public:
Logger(bool aIsTx):isTx_(aIsTx) {init();}
~Logger() {}
uint16_t fbLog(const fileId_t aId, const void *aData, const uint16_t aSz){
if (isTx_)
// do remote logging
return remoteLog(aId, aData, aSz);
else
// do local logging
return fwrite(aData, aSz, 1,fd_[aId]);
}
protected:
bool isTx_
}
What I would like to do is
Some way of removing the if(isTx_) such that the code to be used gets defined at the time of instantiating.
Since the class objects are used by multiple other modules, I would not like to templatize the class because this will require me to wrap two templatized implementations of the class in an interface wrapper which will result in v-table call every time a member function is called.
You cannot "templetize" the behaviour, since you want the choice to be done at runtime.
In case you want to get rid of the if because of performance, rest assured that it will have negligible impact compared to disk access or network communication. Same goes for virtual function call.
If you need low latency, I recommend considering asynchronous logging: The main thread would simply copy the message into an internal buffer. Memory is way faster than disk or network, so there will be much less latency. You can then have a separate service thread that waits for the buffer to receive messages, and handles the slow communication.
As a bonus, you don't need branches or virtual functions in the main thread since it is the service thread that decides what to do with the messages.
Asynchronisity is not an easy approach however. There are many cases that must be taken into consideration:
How to synchronise the access to the buffer (I suggest trying out a lock free queue instead).
How much memory should the buffer be allowed to occupy? Without limit it can consume too much if the program logs faster than can be written.
If the buffer limit is reached, what should the main thread do? It either needs to fall back to synchronously waiting while the buffer is being processed or messages need to be discarded.
How to flush the buffer when the program crashes? If it is not possible, then the last messages may be lost - which probably are what you need to figure out why the program crashed in the first place.
Regardless of choice: If performance is critical, then try out multiple approaches and measure.

Using Critical Sections/Semaphores in C++

I recently started using C++ instead of Delphi.
And there are some things that seem to be quite different.
For example I don't know how to initialize variables like Semaphores and CriticalSections.
By now I only know 2 possible ways:
1. Initializing a Critical Section in the constructor is stupid since every instance would be using its own critical section without synchronizing anything, right?
2. Using a global var and initializing it when the form is created seems not to be the perfect solution, as well.
Can anyone tell me how to achieve this?
Just a short explanation for what I need the Critical Section :
I'd like to fill a ListBox from different threads.
The Semaphore :
Different threads are moving the mouse, this shouldn't be interrupted.
Thanks!
Contrary to Delphi, C++ has no concept of unit initialization/finalization (but you already found out about that).
What we are left with is very little. You need to distinguish two things:
where you declare your variable (global, static class member, class member, local to a function, static in a function -- I guess that covers it all)
where you initialize your variable (since you are concerned with a C API you have to call the initialization function yourself)
Fact is, in your case it hardly matters where you declare your variable as long as it is accessible to all the other parts of your program that need it, and the only requirement as to where you should initialize it is: before you actually start using it (which implies, before you start other threads).
In your case I would probably use a singleton pattern. But C++ being what it is, singletons suffer from race condition during their initialization, there is no clean way around that. So, in addition to your singleton, you should ensure that it is correctly created before you start using it in multithreaded context. A simple call to getInstance() at the start of your main() will do the trick (or anywhere else you see fit). As you see, this takes only care of where you declare your variable, not where you initialize it, but unfortunately C++ has important limitations when it comes to multithreading (it is under-specified) so there is no way around that.
To sum it up: just do what you want (as long as it works) and stop worrying.
In my opinion you only need a critical section to synchronize updates to a list box from various threads. Mouse will keep moving. Semaphore is not fitting the solution. You initialize the critical section in you class constructor. where the list box is. Write a method to update the listbox.
//psudo code
UpdateListBox()
{
//enter critical section
//update
//leave critical section
}
All the threads will call this method to update the listbox.
information about critical section is here
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683472%28v=vs.85%29.aspx

Race condition: One thread creates static object, another thread uses it before it is finished initializing. How to handle?

I have several places in my code where a function static object is created once, and then used (copied) any time that function is called. One of these functions can be called from any thread. The function doesn't access any shared state other than this static object.
When thread 1 calls the function for the first time, the object is created and initialized. However, (by a stroke of luck) I have a repeatable case where the program switches to thread 2 and calls the same function before initialization is finished. The object is assigned, and used, with bad data!
I'm not sure how to handle this. I'm using critical sections in the initialization code, but that's not even the problem. This object is being used before being initialized in the first place.
I tried making this thread local using __declspec(thread), but that doesn't work for objects, apparently.
I could just surround the whole thing with a critical section, and maybe that's the best solution, but I'm concerned about problems like this cropping up in other parts of the code- it'd be nice to have a general solution.
If you are on Windows you could use the InitOnceExecuteOnce API. More details can be found in this Raymond Chen post. Also look at the more generic std::call_once
Couldn't you use a semaphore on the object, setting the semaphore to be already set to 1 when the object is created, and then decrementing it to zero when the object is initialized (and ready for use).
Just need to keep an eye out for resource starvation though.

pthread_key_t and pthread_once_t?

Starting with pthreads, I cannot understand what is the business with pthread_key_t and pthread_once_t?
Would someone explain in simple terms with examples, if possible?
thanks
pthread_key_t is for creating thread thread-local storage: each thread gets its own copy of a data variable, instead of all threads sharing a global (or function-static, class-static) variable. The TLS is indexed by a key. See pthread_getspecific et al for more details.
pthread_once_t is a control for executing a function only once with pthread_once. Suppose you have to call an initialization routine, but you must only call that routine once. Furthermore, the point at which you must call it is after you've already started up multiple threads. One way to do this would be to use pthread_once(), which guarantees that your routine will only be called once, no matter how many threads try to call it at once, so long as you use the same control variable in each call. It's often easier to use pthread_once() than it is to use other alternatives.
No, it can't be explained in layman terms. Laymen cannot successfully program with pthreads in C++. It takes a specialist known as a "computer programmer" :-)
pthread_once_t is a little bit of storage which pthread_once must access in order to ensure that it does what it says on the tin. Each once control will allow an init routine to be called once, and once only, no matter how many times it is called from how many threads, possibly concurrently. Normally you use a different once control for each object you're planning to initialise on demand in a thread-safe way. You can think of it in effect as an integer which is accessed atomically as a flag whether a thread has been selected to do the init. But since pthread_once is blocking, I guess there's allowed to be a bit more to it than that if the implementation can cram in a synchronisation primitive too (the only time I ever implemented pthread_once, I couldn't, so the once control took any of 3 states (start, initialising, finished). But then I couldn't change the kernel. Unusual situation).
pthread_key_t is like an index for accessing thread-local storage. You can think of each thread as having a map from keys to values. When you add a new entry to TLS, pthread_key_create chooses a key for it and writes that key into the location you specify. You then use that key from any thread, whenever you want to set or retrieve the value of that TLS item for the current thread. The reason TLS gives you a key instead of letting you choose one, is so that unrelated libraries can use TLS, without having to co-operate to avoid both using the same value and trashing each others' TLS data. The pthread library might for example keep a global counter, and assign key 0 for the first time pthread_key_create is called, 1 for the second, and so on.
Wow, the other answers here are way too verbose.
pthread_once_t stores state for pthread_once(). Calling pthread_once(&s, fn) calls fn and sets the value pointed to by s to record the fact it has been executed. All subsequent calls to pthread_once() are noops. The name should become obvious now.
pthread_once_t should be initialized to PTHREAD_ONCE_INIT.