Can I use threads to change a GTK image? - c

I have a GTK window with an image inside of it. I want this image to change. Let's say I have two images, "sun.png" and "moon.png". Once every second, I want to receieve the output of "date -f%l" to get the current hour. If the hour is between 7-19 (7 AM to 7 PM), I want to display sun.png. Else, I want to display moon.png.
Is it possible to have a seperate thread with a while loop in it, that changes the image as the program's running? How would I go about doing this?
I'm writing in C, by the way.

This isn't going to be a complete answer, but it's too long for a comment and it's important.
You definitely do not implement something like this by going into a loop sleeping for one second at a time and calling the external date command and parsing its output to determine what to do next. Not only is this a lot more work than is necessary; more importantly, it will eat your users' batteries for dinner.
Instead, you call gettimeofday or clock_gettime to determine the current time, then compute the next time in the future that the sun/moon image will need to be changed. Then, you sleep the whole interval until that time, i.e. up to 12 hours in a single sleep. If your thread wakes up early (perhaps from signals, etc.) then you just determine, on calling gettimeofday again, that it's not yet time to change, and compute a new duration of time to go back to sleep. This way, the CPU remains completely idle (and can go into powersaving mode) except when there's actually work to be done.
As for whether you can do this with a thread at all in GTK+, I'm pretty sure you can, but I'm not familiar with the GTK+ API.

Related

Is there a way to call a function n times per second while compensating for drift?

I've seen a lot of answers to very similar questions, but they all seem to resort to using something like a sleep(1/n) call at the end of a function or in some cases timing the function and calling sleep((1/n) - functionTime). Surely there is a better way to do this? Modern hardware has access to precise hardware timers that can send an interrupt to the CPU some known number of times per second, is there no way to take advantage of these timers to run a function such as a physics engine update a known, fixed number of times per second from user space code? What I would like to do in particular is, preferably in C or C++, define some function, let's call it foo(), and designate it to be called N times per second. I would want to be able to know that if M seconds have passed, foo will have been called N*M times assuming foo() ran in less than 1/N seconds on average.
There is no standard C API for scheduling calls.
You probably want to have a separate thread that runs every 1/Nth of a second.
In the pthreads world, this can be done with pthread_cond_timedwait. This function expects the absolute time to wake up. In addition, some other thread can wake it up using the condition variable if some unplanned update needs to be made.
In the Windows world you probably need one of the WaitFor<whatever> functions. They expect a relative timeout, so you want to convert absolute time to relative time-interval-from-now yourself. In this case, too, another thread is able to wake you up to perform an urgent update.
The absolute time you need is just the absolute time the previous call was scheduled for, plus 1/Nth of a second. The very first one can be set to the current time just before the call.

How often does a processor check if time on a timer is up to execute a program?

For example, if we program a computer to check and update some variables every 5 minutes does that mean that the computer actually checks if the condition matches (if that 5 minutes are up so it can execute a program) every tick? So that means (in my point of view) the bigger the amount of conditionals or timers or both the heavier the load on the processor even though the processor just checks if the time is up or whether the condition is match or not.
My reasoning being here that the processor can't really put some task away and forget about it for 5 minutes and then just remember about it and execute the program. It has to keep a track of time (counting seconds or ticks or whatever), keep track of timers that are currently being on and check if the time on every timer is up or not.
That makes every timer a conditional statement. Right?
So the main question is... am I correct on all of those statements or the reality is a bit different and if so then how different?
Thank you.
I am assuming here that you have a basic understanding of how processes are managed in a CPU
Most programming languages implement some form of wait() function, that will cause the CPU to stop executing instructions from that thread until it is interrupted, allowing it to work on other tasks in the meantime. Waiting for an interrupt does not use much of the system's resources, and is much more efficient than the polling method that you were describing.
This is a pretty basic explanation, but if you want to learn more, lookup preemptive multitasking.

Changing system time causes application to hang LINUX (LUBUNTU) TCL/TK

I have a tcl/tk with c desktop application, and one of the requirements is to change the system time, in the background there are threads running from the c code, and "after" commands from the tcl code. Whenever I change the time to an earlier time the system hangs
i.e: 05:50:12 -> 05:45:12 also i get weird behavior when going forward in time. I'm running lubuntu. I'm not sure what to do in this situation, I made some test and it seems the after keeps on waiting after i change back in time.
to change the time i use : exec date --set="STRING" from the tcl code
Tcl depends on the system time (converted to seconds from the start of the Unix epoch) increasing fairly close to monotonically for the correct behaviour of a number of things, but most particularly anything in the after command. Internally, after computes the absolute time that an event should happen and only triggers things once that time is reached, so that things being triggered early (which can happen because of various OS events) don't cause problems. If you set the system time back a long way, Tcl will wait until the absolute time is reached anyway, which will look a lot like a hang.
Just synch your clock with NTP (i.e., switch on ntpd) and stop fiddling with the system clock by hand.

Using threads, how should I deal with something which ideally should happen in sequential order?

I have an image generator which would benefit from running in threads. I am intending to use POSIX threads, and have written some mock up code based on https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal to test things out.
In the intended program, when the GUI is in use, I want the generated lines to appear from the top to the bottom one by one (the image generation can be very slow).
It should also be noted, the data generated in the threads is not the actual image data. The thread data is read and transformed into RGB data and placed into the actual image buffer. And within the GUI, the way the thread generated data is translated to RGB data can be changed during image generation without stopping image generation.
However, there is no guarantee from the thread scheduler that the threads will run in the order I want, which unfortunately makes the transformations of the thread generated data trickier, implying the undesirable solution of keeping an array to hold a bool value to indicate which lines are done.
How should I deal with this?
Currently I have a watcher thread to report when the image is complete (which really should be for a progress bar but I've not got that far yet, it instead uses pthread_cond_wait). And several render threads doing while(next_line());
next_line() does a mutex lock, and gets the value of img_next_line before incrementing it and unlocking the mutex. it then renders the line and does a mutex lock (different to first) to get lines_done checks against height, signals if complete, unlocks and returns 0 if complete or 1 if not.
Given that threads may well be executing in parallel on different cores it's pretty much inevitable that the results will arrive out of order. I think your appraoch of tracking what's complete with a set of flags is quite reasonable.
It's possible that the overall effect might be nicer if used threads in a different granularity. Say give each thread (say) 20 lines to work on rather than one. Then on completion you'd have bigger blocks available to draw, and maybe drawing stripes would look ok?
Just accept that the rows will be done in a non-deterministic order; it sounds like that is happening because they take different lengths of time to render, in which case forcing a completion order will waste CPU time.
This may sound silly but as a user I don't want to see one line rendered slowly from top to bottom. It makes a slow process seem even slower because the user already has completely predicted what will happen next. Better to just render when ready even if it is scattered over the place (either as single lines or better yet as blocks as some have suggested). It makes it look more random and therefore more captivating and less boring to a user like me.

glutPostRedisplay in a different thread

I have a standard glut implementation. The display function redraws each object, but I need a constant update on certain values of each object. As it is, the only way I can think to do this is to spawn a thread to handle the updating. However, I can't use glutPostRedisplay() from a different thread to get glut to refresh the window. What is a good way to have a loop to update values alongside the glut loop?
Also, what's the best way to sleep for fractions of seconds (instead of sleep() for whole seconds).
If you need some sort of regular updating, you probably want to set a glutIdleFunc. This is a function that will get called in a loop whenever there are no events coming in to be processed. If you instead want to call something at regular intervals (as opposed to as fast as possible), you might want to try glutTimerFunc which allows you to schedule something to be run by the GLUT loop some number of milliseconds in the future.
As for your second question, if you need to sleep for fractions of seconds, you might want to try usleep for microsecond resolution sleep periods, or nanosleep to specify sleep periods in nanoseconds (though you're not actually going to get nanosecond resolution). I don't know what platform you're on or if these are available on Windows, but they should be available on any POSIX compatible system (Linux, BSD, Mac OS X). But perhaps for your purposes glutTimerFunc will work better.
edit to add: It looks like on Windows you would need to use [Sleep](http://msdn.microsoft.com/en-us/library/ms686298(VS.85%29.aspx) (note the capital S), which takes a time in milliseconds.

Resources