freeRTOS: How to pass data between tasks? [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am looking for an example that present a proper way to pass data between tasks:
Lets say I have a display, keyboard and some sensors eg. internal ADCs.
I would like to show values from all sensors at some time on a display. After pressing a button, changing a view and presenting some text. After pressing another, going back to values.
I would use global variables, but it is described everywhere as a bad idea. On the other hand, if I used Queues (xQueueCreate, xQueueReceive, xQueueSend), I wouldnt have all data to display it and I believe that creating a copy after receiving them is just losing memory.

You already mentioned some of possible solutions, but saying that you're loosing memory because you copy data, it's always the case if you want to secure this data from i.e. writing from two different places, anyway just by using FreeRTOS you already decided to loose a lot of memory for i.e. context switching, task handling and all other resources that FreeRTOS uses. Possible solutions are:
Global variable - The reason's why it's a bad idea, is because
ideally you want to limit access to variable (scope). As well it's hard to
keep it safe, because during task switch other task could write to
the same variable, and possible corrupt your data. But if you
protect it right i.e. lock the variable using some kind of flag,
it's perfectly fine solution, and using i.e. sempahore or queue to notify display task that data is filled.
Queues - you could send from multiple tasks and as you said keeping in display task copy of variables, it's much safer option, and it doesn't have to be loosing memory, because you don't have to store it any other place, you could just read sensor, then put it in queue, and then when you received it in display task you change your previous value. So task which read's data from let's say ADC doesn't need to store it in between reads.
Queues - but a little bit different that you proposed, if you got direct flow in system let's say first you check keyboard, then sensor, then something else you could send queue with struct from TASK1 -> TASK2 -> TASK3 -> ... TASKX -> DISPLAY_TASK this way variable would have certain flow, and you would make sure that you always have all data in one place.
You could use the same paramater in all structs (pvParameters in taskCreation), so you would point to the same structure, in this case to protect data you could use mutex during write to variable (so you know only 1 task at a time got access to this variable). You could use mutex in global variable option as well.

Related

What is the most efficient way to take in user input with many options in C? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am writing a weather program that calls an API for data. One of the flags available is a preferred language, of which there are about 45 options. This leads me to the question.
What is the most efficient way to display all the language options, then allow user input, then check for valid input?
My best idea is a loop that prints all the options from a file. The user then inputs an option. Their selection is checked against the list to find a match. If there is a match then the program continues. If not, they are prompted again.
Is this the best way to go about this? I'm trying to make this program as efficient and professional looking as possible as I'm using it for my portfolio.
My best idea is a loop that prints all the options from a file. The user then inputs an option. Their selection is checked against the list to find a match. If there is a match then the program continues. If not, they are prompted again.
Is this the best way to go about this? I'm trying to make this program as efficient and professional looking as possible as I'm using it for my portfolio.
There are always multiple competing goals (single-thread performance, scalability, features, flexibility/extendibility, code readability, fault tolerance). For well designed code, its good to understand the importance of each of these goals for each piece of code (and good to understand that these importances can be different for different pieces of code in the same project). For this specific piece of code; I'd say that flexibility/extendibility (e.g. the ability to add new languages easily later) is the most important, followed by code readability (the ability to understand the code later, and find/fix bugs in it). The least important are scalability (e.g. how much performance increases when number of CPUs increases) then single-thread performance; because the code only needs to work once and is held back by the speed that a human can type anyway.
Is this the best way to go about this? I'm trying to make this program as efficient and professional looking as possible as I'm using it for my portfolio.
In terms of "human computer interaction"; the best way is to make it impossible for the user to enter invalid data (e.g. a drop down list with a well predicted default to avoid the need for a "not set yet" option). The second best way is "active status" - specifically, for every "user input event" (key press, mouse click, etc) a status field corresponding to the input field/control is updated to either indicate that the field/input is in an acceptable state, or provide the reason why it's not; where its impossible for the user to continue (e.g. because an "OK" button is disabled) until all of status fields are saying that the input is acceptable. For both of these options there is no need to validate the submitted input afterwards.
Sadly; for "command line", it's almost impossible to use the best way and almost impossible to use the 2nd best way.
In other words; you need to forget about performance/efficiency (because that's the least important); and then forget about writing software that is good/user-friendly (because it's command line).
The question then is; what is the "least bad" option? For this; I'd start by assuming that the data for each language is stored in a separate file (or directory?) where the file name is usable for display purposes; and all of the data is in a specific directory (e.g. a "project/lang" directory that contains a "project/lang/UK_English" file, a "project/lang/Spanish" file, etc). In this case you can get a list of files in the "project/lang" directory, sort them in alphabetical order, and use them to display a list of numbered options ("1) Spanish", "2) UK English", ..). Then if/when the user selects an option you can validate it (and report any errors if the user entered a bad character, a number that's too high, etc, then ask the user to retry); and load the right file for whichever language they chose (and report any errors if there's a problem with the file and ask the user to choose something else).
That way; people/translators can just create new files, and none of the code will need to be modified.
For a comparison; the fastest way is to use constant strings (e.g. puts("1) Spanish\n2) UK English\n\nEnter language choice:")); and to predict what the user will choose (e.g. based on keeping track of what they chose last time) and "pre-fetch and pre-parse" in the background (so that hopefully all the work is done for the correct choice before the user actually makes a choice), with the ability to quickly cancel the "pre-fetch and pre-parse" work if the user makes a choice that wasn't predicted. This would be extremely good for performance (likely "instant") but extremely bad (inflexible, over-complicated, too hard to maintain).

What is better: a single BAO or multiple BAOs [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
So I'm currently learning OpenGL, and while working through some of the tutorials, I've noticed that most of them create multiple buffer-array-objects (BAO) for the vertex-positions, normal-vectors and uv-coordinates. But there is also the option to just create a single BAO, where each element includes all the necessary information about a single vector. So what's the "good" or rather "recommended" way of doing things? Create multiple ones or just a single one?
From Buffer Object - OpenGL Wiki (recommended reading):
Buffer Object Usage
Buffer objects are general purpose memory storage blocks allocated by OpenGL. They are intended to be used in a great many ways. To give the implementation great flexibility in exactly what a particular buffer object's data store will be, so as to better optimize performance, the user is required to give usage hints. These provide a general description as to how exactly the user will be using the buffer object.
BO's are shared between the client and the server (in OpenGL terms). How many of them you should use, is entirely up to you. Your instincts seem to be good however. You should never optimize before you just get it working. But after you've had some experience with OpenGL, you'll probably find there are use cases, where a little early optimization can save you a lot of refactoring later on.
I can't help you much with where to draw those lines, but I would say that you should think first, about what and when you intend to render as execution progresses.

Why should I use thread-specific data?

Since each thread has its own stack, its private data can be put on it. For example, each thread can allocate some heap memory to hold some data structure, and use the same interface to manipulate it. Then why thread-specific data is helpful?
The only case that I can think of is that, each thread may have many kinds of private data. If we need to access the private data in any function called within that thread, we need to pass the data as arguments to all those functions, which is boring and error-prone.
Thread-local storage is a solution for avoiding global state. If data isn't shared across threads but is accessed by several functions, you can make it thread-local. No need to worry about breaking reentrancy. Makes debugging that much easier.
From a performance point of view, using thread-local data is a way of avoiding false sharing. Let's say you have two threads, one responsible for writing to a variable x, and the other responsible for reading from a variable y. If you were to define these as global variables, they could be on the same cache line. This means that if one of the threads writes to x, the CPU will update the cache line, and this of course includes the variable y, so cache performance will degrade, because there was no reason to update y.
If you used thread-local data, one thread would only store the variable x and the other would only store the variable y, thus avoiding false sharing. Bear in mind, though, that there are other ways to go about this, e.g. cache line padding.
Unlike the stack (which, like thread-local data is dedicated to each thread), thread-local data is useful because it persists through function calls (unlike stack data which may already be overwritten if used out of its function).
The alternative would be to use adjacent pieces of global data dedicated to each thread, but that has some performance implications when the CPU caches are concerned. Since different threads are likely to run on different cores, such "sharing" of a global piece of data may bring some undesirable performance degradation because an access from one core may invalidate the cache-line of another, with the latter contributing to more inter-core traffic to ensure cache consistency.
In contrast, working with thread-local data should conceptually not involve messing up with the cache of other cores.
Think of thread local storage as another kind of global variable. It's global in the sense that you don't have to pass it around, different code can access it as they please (given the declaration of course). However, each different thread has its own separate variable. Normally, globals are extra bad in multithreaded programming bacause other threads can change the value. If you make it thread local, only your thread can see it so it is impossible for another thread to unexpectedly change it.
Another use case is when you are forced to use a (badly designed) API that expects you to use global variables to carry information to callback functions. This is a simple instance of being forced into a global variable, but using thread local storage to make it thread safe.
Well, I've been writing multithreaded apps for 30 odd years and have never, ever found any need to use TLS. If a thread needs a DB connection that the DB binds to the thread, the thread can open one of its own and keep it on the stack. Since threads cannot be called, only signaled, there is no problem. Every time I've ever looked at this magic 'TLS', I've realized it's not a solution to my problem.
With my typical message-passing design, where objects are queued in to threads that never terminate, there is just no need for TLS.
With thread-pools it's even more useless.
I can only say that using TLS=bad design. Someone put me right, if you can :)
I've used thread local storage for database connections and sometimes for request / response objects. To give two examples, both from a Java webapp environment, but the principles hold.
A web app might consist of a large spread of code that calls various subsystems. Many of these might need to access the database. In my case, I had written each subsystem that required the db to get a db connection from a db pool, use the connection, and return the connection to the pool. Thread-local storage provided a simpler alternative: when the request is created, fetch a db connection from the pool and store it in thread-local storage. Each subsystem then just uses the db connection from thread-local storage, and when the request is completing, it returns the connection to the db pool. This solution had performance advantages, while also not requiring me to pass the db connection through every level: ie my parameter lists remained shorter.
In the same web app, I decided in one remote subsystem that I actually wanted to see the web Request object. So I had either to refactor to pass this object all the way down, which would have involved a lot of parameter passing and refactoring, or I could simply place the object into Thread Local storage, and retrieve it when I wanted it.
In both cases, you could argue that I had messed up the design in the first place, and was just using Thread Local storage to save my bacon. You might have a point. But I could also argue that Thread Local made for cleaner code, while remaining thread-safe.
Of course, I had to be very sure that the things I was putting into Thread Local were indeed one-and-only-one per thread. In the case of a web app, the Request object or a database connection fit this description nicely.
I would like to add on the above answers, that as far as I know, performance wise, allocation on stack is faster than allocation on heap.
Regarding passing the local data across calls , well - if you allocate on heap, you will need to pass the pointer / reference (I'm a Java guy :) ) to the calls - otherwise, how will you access the memory?
TLS is also good in order to store a context for passing data across calls within a thread (We use it to hold information on a logged on user across the thread - some sort of session management).
Thread Specific Data is used when all the functions of a particular thread needs to access one common variable. This variable is local to that particular thread but acts as a global variable for all the functions of that thread.
Let's say we have two threads t1 and t2 of any process. Variable 'a' is the thread specific data for t1. Then, t2 has no knowledge over 'a' but all the functions of t1 can access 'a' as a global variable. Any change in 'a' will be seen by all the functions of t1.
With new OOP techniques available, I find thread specific data as irrelevant. Instead of passing the function to the thread, you can pass the functor. The functor class that you pass, can hold any thread specific data that you need.
Eg. Sample code with C++11 or boost would like like below
MyClassFunctor functorobj; <-- Functor Object. Can hold the function that runs as part of thread as well as any thread specific data
boost::thread mythread(functorobj);
Class MyClassFunctor
{
private:
std::list mylist; <-- Thread specific data
public:
void operator () ()
{
// This function is called when the thread runs
// This can access thread specific data mylist.
}
};

MPQueue - what is it and how do I use it?

I encountered a bug that has me beat. Fortunately, I found a work around here (not necessary reading to answer this q) -
http://lists.apple.com/archives/quartz-dev/2009/Oct/msg00088.html
The problem is, I don't understand all of it. I am ok with the event taps etc, but I am supposed to 'set up a thread-safe queue) using MPQueue, add events to it pull them back off later.
Can anyone tell me what an MPQueue is, and how I create one - also how to add items and read/remove items? Google hasn't helped at all.
It's one of the Multiprocessing Services APIs.
… [A] message queue… can be used to notify (that is, send) and wait for (that is, receive) messages consisting of three pointer-sized values in a preemptively safe manner.

Should a cancel button ask for confirmation? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
If a user clicks a cancel button should it pop up a dialogue asking for confirmation?
If so, should this be all the time, or only when there are unsaved changes on a form?
No unless it's something that is very vital/potentially harmful. Having popups followed by popups is annoying.
If canceling the action will destroy data or a device, yes. For instance, canceling in the middle of upgrading the firmware of some device.
If the action being performed takes a long time and an accidental cancelation will require starting over, yes.
For instance, I don't find the pop-up here on StackOverflow annoying when I decide to close a tab rather than making an edit I started on one of my questions.
"Cancel" means to give up on an action before it begins. If the action has already started, the command should be named "Stop" instead. That makes it clear to the user that the button might interrupt something in mid-stream.
A real Cancel action doesn't need confirmation because it doesn't cause any problems. A Stop action might, but only if stopping partway through could leave things in a messed-up state. (And in that case, you should consider finding a way to have the stop back out all the already-made changes so that the state reverts back to what it was before the action began. This isn't always possible, of course, like if you're deleting files.)
It really depends on the situation.
Encoding a video for example, a process that may take hours, should have a confirmation, just because you may accidentally hit the button at 99%.
The initialization process of an installer or other app, on the other hand, doesn't need a confirmation since it can typically be restarted quickly enough and doesn't take long to begin with.
If clicking Cancel starts a process that will potentially take a long time (let's say it needs to reverse changes), the user should be informed about that, possibly with a popup, but some text next to the button might suffice as well.
The general rule is to minimize Confirmation Dialogs as much as possible, if for example it could be replaced with an Undo action. I don't think this applies to most Cancel buttons though.
Use the following algorithm to determine the answer to your question:
if (1-p)*w > p*a then ask for confirmation
where
p is the probability that the user really wanted to cancel (0.7 or so)
w is the amount of lost (work-) time due to inadvertent cancelling
a is the time lost due to an anoying confirmation (5 seconds or so)
Of course you have to estimate p, w and a. Using my default values, you should ask for confirmation when unintentional canceling would cost the user more than 10.5 seconds of time.
So, in the case of a long-time operation, e.g. encoding a video, you shouldn't ask if the user clicks cancel within 10 seconds after starting that task. In the case of data entry, don't ask if the form is still completely empty, but ask if the user has already entered data.
Make the action easy to do without confirmation (don't annoy your users!). But, also make it easy to undo. Read Alan Cooper's About Face for lots of good UI advice.
Basically, if undo-ing a cancel is difficult, time-consuming, or impossible, you should prompt the user. Those are usually the case when the user has done some actions that they might wish to preserve (e.g. writing a blog post and closing a tab, updating firmware on a hardware device, running system updates, installing large pieces of software) instead of just deleting the current state. After all, sometimes the cancel button may be clicked accidentally. You just need to use common sense to determine whether it would be a really bad experience for the user if an operation was accidentally cancelled (which would call for a cancel prompt), or whether they could easily restart whatever operation was accidentally cancelled without much loss. The strategy I use for solving such problems is by putting myself in the user's shoes, i.e. imagining myself as a user of this program. How would I feel if I accidentally clicked cancel??? If that mentality is grim, add a prompt in case.
It would be better to not prompt, but make it easy to undo the cancellation once it is done, if possible. GMail does this well. You click 'Delete', it deletes, but you get a link at the top to say 'Undo delete'.
I think the answer in terms of data.
If user made changes on data , not talking about clicking somewhere on interface, user should be asked to confirm exiting.
But if no change happenned, no reason for confirmation. Because confirmation is an effort for user.

Resources