I have a program in C++. I want to call a function asynchronously with a configurable wait time before.
My idea of a solutions is to create a thread and in the body I would wait for the configured time and then call the needed function and then destroy the thread again.
The overhead seams very high to me, creating a separate thread. Is there a better solution (less overhead) like a timer to call the function later?
You could use your operating system.
On Windows you can use the WinAPI SetTimer, on Linux use timerfd or timer_create.
Related
I am implementing a function in library which takes a while (up to a minute). It initialize a device. Now generally any long function should run in its own thread and report to main thread when it completes but I am not sure since this function is in library.
My dilemma is this, even if I implement this in a separate thread, another thread in the application has to wait on it. If so why not let the application run this function in that thread anyways?
I could pass queue or mailbox to the library function but I would prefer a simpler mechanism where the library can be used in VB, VC, C# or other windows platforms.
Alternatively I could pass HWND of the window and the library function can post message to it when it completes instead of signaling any event. That seems like most practical approach if I have to implement the function in its own thread. Is this reasonable?
Currently my function prototype is:
void InitDevice(HANDLE hWait)
When initialization is complete than I signal bWait. This works fine but I am not convinced I should use thread anyways when another secondary thread will have to wait on InitDevice. Should I pass HWNDinstead? That way the message will be posted to the primary thread and it will make better sense with multithreading.
In general, when I write library code, I normally try to stay away from creating threads unless it's really necessary. By creating a thread, you're forcing a particular threading model on the application. Perhaps they wish to use it from a very simplistic command-line tool where a single thread is fine. Or they could use it from a GUI tool where things must be multi-threaded.
So, instead, just give the library user understanding that a function call is a long-term blocking call, some callback mechanism to monitor the progress, and finally a way to immediately halt the operation which could be used by a multi-threaded application.
What you do want to claim is being thread safe. Use mutexes to protect data items if there are other functions they can call to affect the operation of the blocking function.
Is there any way to write a timer in pure C/C++ with only using pthreads neither boost nor Qt.
I want OS to run only the function in the relevant thread(e.g MyThreadClass.myfunction()). I don't want to check the signal in every thread(there must be 1 type of thread cheking time). The timer thread must run (by interrupting other processes and threads) at the time as soon as possible and be able to calculate the time elapsed at it is not running. And it must not use while(true) like loops I don't want to make CPU busy.
For example I set my thread to run in 100ms. It goes background and checks time. It should run frequent but short. At 100ms it will interrupt threads and runs a particular function.
You'll have to be more specific about why you need to use only pthreads. The following uses librt which is part of the included system libraries on most POSIX systems.
Sounds like you want to use timer_create with the SIGEV_THREAD argument. That will create a thread and run a specified function when the timer expires.
While profiling my code to find what is going slow, I have 3functions that are taking forever apparently, well thats what very sleepy says.
These functions are:
ZwDelayExecution 20.460813 20.460813 19.987685 19.987685
MsgWaitForMultipleObjects 20.460813 20.460813 19.987685 19.987685
WaitForSingleObject 20.361805 20.361805 19.890967 19.890967
Can anybody tell me what these functions are? Why they are taking so long, and how to fix them.
Thanks
Probably that functions are used to make thread 'sleeping' in Win32 API. Also they might be used as thread synchronization so check these thing.
They are taking so much CPU time because they are designed for that.
The WaitForSingleObject function can wait for the following objects:
Change notification
Console input
Event
Memory resource notification
Mutex
Process
Semaphore
Thread
Waitable timer
So the other possible thing where it can be used for is console user input waiting.
ZwDelayExecution is an internal function of Windows. As it can be seen it is used to realize Sleep function. Here is call stack for Sleep function so you can see it with your own eyes:
0 ntdll.dll ZwDelayExecution
1 kernel32.dll SleepEx
2 kernel32.dll Sleep
It probaly uses Assembly low-level features to realize that so it can delay thread with precision of 100ns.
MsgWaitForMultipleObjects has a similar to WaitForSingleObject goal.
Judging on the names, all 3 functions seem to block, so they take a long time because they are designed to do so, but they shouldn't use any CPU while waiting.
One of the first steps should always be to check the documentation:
WaitForSingleObject:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687032.aspx
Waits for an object like a thread, process, mutex.
MsgWaitForMultipleObjects:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684242.aspx
Simply waits for multiple objects, just like WaitForSingleObject.
ZwDelayExecution:
There doesn't seem to be a documentation for ZwDelayExecution but I think that is an internal method which get's called when you call Sleep.
Anyway, the name already reveals part of it. "Wait" and "Delay"-functions are supposed to take time. If you want to reduce the waiting time you have to find out what is calling these functions.
To give you an example:
If you start a new thread and then wait for it to finish in your main thread, you will call WaitForSingleObject one way or another in WINAPI-programming. It doesn't even have to be you who is starting the thread - it could be the runtime itself. The function will wait until the thread finishes. Therefore it will take time and block the program in WaitForSingleObject until thread is done or a timeout occurs. This is nothing bad, this is intended behaviour.
Before you start zooming in on these functions, you might first want to determine what kind of slowness your program is suffering from. It is pretty normal for a Windows program to have one or more threads spending most of their time in blocking functions.
You would first need to determine whether your actual critical thread is CPU bound. In that case you don't want to zoom in on the functions that take a lot off wall clock time, you want to find those functions that take CPU time.
I don't have much experience with Very Sleepy, but IIRC it is a sampling profiler, and those are typically not so good at measuring CPU usage.
Only after you've determined that your program is not CPU bound, then you should zoom in on the functions that wait a lot.
I need a function(eg signal handler) in C/C++ linux that gets activated every 'n' milliseconds. How do I setup signals etc...to register to timer events at the millisecond resolution.
Accuracy is not super critical, but need within hundred ms or so.
I am new to linux and I really don't know where to start.
A much safer alternative to setitimer (which POSIX 2008 marks OBSolete) would be to use POSIX timers, and have the timer expiration function run in a thread rather than a signal handler. This way you are not restricted to only using async-signal-safe functions. They're documented here:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_08_05
If you don't like the POSIX timers API, you could instead create a thread that merely sleeps in a loop, and block the timer signal in all threads except that thread. Then you will be free to use whatever functions you like in the signal handler, since it will run in a separate thread and there is no danger of it interrupting an async-signal-unsafe function.
setitimer(2) is a good start, but do you really want to go asynchronous with signals? Otherwise, you could have a main loop with select(2) or poll(2) and an appropiate timeout.
Someone suggested to me to use Call Back Functions to implement a timer to run in the background while my Server application reads input from clients. I tried looking at explanations online, but was hoping if someone could give me a simpler analogy.
Thanks.
There are two separate ways to implement a timer using callbacks in Windows, SetTimer and timeSetEvent. The basics are:
SetTimer uses messages, even if you use a callback (the callback function is invoked as a result of processing a message). So SetTimer isn't viable if you don't run a message pump.
Callbacks are called by the operating system, which doesn't know a C++ "this" pointer from a hole in the ground, so your callback either has to be a global C-style function or a static member.
timeSetEvent is part of the "multimedia" timer family, and doesn't require a message pump. The observations about the callback function signature above still apply though. The lack of requirement for a message pump can be important if you're writing a console app though.
You might also consider threading and CreateWaitableTimer, but I don't use waitable timers very often so can't comment on them.
If you need to do work in the background, then threading can be a much more elegant way to address the problem. You don't have to divide the work up into chunks when you're threading (which you do if you're kicking the work from a timer). But of course your thread can't touch the GUI, so life can get a little complicated when you start threading. There's an intro to worker threads on my website here.
Analogy?
Take a look here for a brief explanation of callback functions:
What is a “callback” in C and how are they implemented?
Using a timer with a callback would be saying 'call function x every y seconds' and with a system that supports multitasking, that function would be called every y seconds in a second thread of execution, no matter what the original function might be doing.
Edit: As has been suggested in another answer, the system might not create a second thread for you, in which case you'd have to create the thread yourself and set up the callback from that thread.
Edit: In Windows, you can use the SetTimer function. It will post a WM_TIMER message to your window's message queue, which your message loop might handle itself or hand over to the default message procedure to call a callback function you've specified. I'm not sure what happens if you don't have a window, but give it a try.
Your question is fairly unclear, but it's probable they were suggesting you create a thread and run your function in that thread.
This can be done by subclassing a system-specific Thread class; by constructing the same class with some sort of call-back function as an argument; by creating a timer that invokes a callback function after some time limit... without a more specific question I can't give more specific advice.