start a freeRTOS task with a function - task

is it safe to create a task with a variable?
TaskHandle_t blablaTaskHandle= NULL;
...
bool startTask = readAVariable();
if(startTask ){
xTaskCreate(&blabla, "blabla", 2048, NULL, 2, &blablaTaskHandle);
}
And also suspend it and resume:
// this is in the main loop
bool suspendTask = true;
if( suspendTask && (blablaTaskHandle!= NULL)){
vTaskSuspend(blablaTaskHandle);
}
else{
vTaskResume(blablaTaskHandle);
}

You create a task with a function call, not a variable, so I'm not sure what you are asking. From the API documentation, and the hundreds of provided examples, it looks like your use of the first parameter to xTaskCreate() is probably wrong.

Related

Dart streams error with .listen().onError().onDone()

I have an issue with some code that looks like this. In this form I have an error
The expression here has a type of 'void', and therefore can't be used.
Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.dart(use_of_void_result).
If I remove the .onDone() the error goes away. Why? ELI5 please :-)
I was looking at https://api.dart.dev/stable/2.7.0/dart-async/Stream/listen.html but seem to still be misundertanding something.
I also read https://api.dart.dev/stable/2.7.0/dart-async/StreamSubscription/onDone.html
serviceName.UploadThing(uploadRequest).listen((response) {
uploadMessageOutput = response.message;
if (response.uploadResult) {
showSuccess();
} else {
showError();
}
getUploadFileList(event);
isSaveInProgress = false;
}).onError((error) {
isSaveInProgress = false;
_handleFileUploadError(uploadRequest, error);
}).onDone(() {
isSaveInProgress = false;
});
Your code is almost right, but will only require a simple change to work correctly.
You would be seeing the same error if you swapped the ordering of onError and onDone, so the issue has nothing to do with your stream usage. However, you're attempting to chain together calls to onError and then onDone which won't work since both of these methods return void.
What you're looking for is cascade notation (..), which will allow for you to chain calls to the StreamSubscription returned by listen(). This is what your code should look like:
serviceName.UploadThing(uploadRequest).listen((response) {
uploadMessageOutput = response.message;
if (response.uploadResult) {
showSuccess();
} else {
showError();
}
getUploadFileList(event);
isSaveInProgress = false;
})..onError((error) { // Cascade
isSaveInProgress = false;
_handleFileUploadError(uploadRequest, error);
})..onDone(() { // Cascade
isSaveInProgress = false;
});

Replace busy waiting with condition variable

How can I replace the below busy waiting with condition variables?
while (this_thread != pthread_self()){
pthread_mutex_lock(&lock);
if(this_thread == -1)
this_thread = get_id();
pthread_mutex_unlock(&lock);
}
Thanks!
Assuming the value returned by get_id() is only set via a function called set_id(), please see this pseudo code:
globals
Mutex mutex
Condition cond
Id id
code
set_id(id_in)
{
mutex_lock
id = id_in
cond_signal
mutex_unlock
}
test()
{
mutex_lock
while ((this_thread = get_id()) != pthread_self())
cond_wait
mutex_unlock
}

Task with infinite cycle

I'm new in C#, I've gone to it from Delphi. So may be I do something wrong. My app (windows service) make tasks to control on-off states and count "on" time. I've tried to use Task.Delay(x), but it seems I catch deadlocks...
Main idea make tasks with infinite cycle which performs every x ms. I don't know if I could use the Timer for executing part code in lambda method of task...?
int TagCnt = DataCtrl.TagList.Count;
stopExec = false;
if (TagCnt != 0)
{
tasks = new Task[TagCnt];
for (int i = 0; i <= TagCnt - 1; i++)
{
int TempID = i;
tasks[TempID] = Task.Run(async () => // make threads for parallel read-write tasks // async
{
Random rand = new Random();
TimeSpan delay = TimeSpan.FromMilliseconds(rand.Next(1000, 1500))
try
{
while (!stopExec)
{
cToken.ThrowIfCancellationRequested();
//do basic job here
await Task.Delay(delay, cToken);
}//while end
}
catch (...)
{
...
}
}, cToken);
}
A couple of things went wrong here:
The tasks you're creating are completed instantly, in your case Task.Factory.StartNew returns Task<Task> because of the async lambda. To make it work as expected, unwrap the inner task with Task.Unwrap. Also, remove TaskCreationOptions.LongRunning, you don't need it here:
tasks[TempID] = Task.Factory.StartNew(async () => { ...}).Unwrap();
Alternatively, use Task.Run, it unwraps automatically (more about this):
tasks[TempID] = Task.Run(async () => { ...});
Besides, there's no synchronization context installed on a Windows service thread by default. Thus, the code after await Task.Delay() will be executing on a new pool thread each time, you should be ready for this.
Task.Delay is a bit different from a periodic timer. It will delay the execution. Use Stopwatch to calculate how much to delay for:
// beginning of the loop
stopwatch.Reset();
stopwatch.Start();
// the loop body
// ...
// end of the loop
await Task.Delay(Math.Max(500-Stopwatch.ElapsedMilliseconds, 0));

How to wait for 3 seconds in ActionScript 2 or 3?

Is there any way to implement waiting for, say, 3 seconds in ActionScript, but to stay within same function? I have looked setInterval, setTimeOut and similar functions, but what I really need is this:
public function foo(param1, param2, param3) {
//do something here
//wait for 3 seconds
//3 seconds have passed, now do something more
}
In case you wonder why I need this - it is a legal requirement, and no, I can't change it.
Use the Timer to call a function after 3 seconds.
var timer:Timer = new Timer(3000);
timer.addEventListener(TimerEvent.TIMER, callback); // will call callback()
timer.start();
To do this properly, you should create the timer as an instance variable so you can remove the listener and the timer instance when the function is called, to avoid leaks.
class Test {
private var timer:Timer = new Timer(3000);
public function foo(param1:int, param2:int, param3:int):void {
// do something here
timer.addEventListener(TimerEvent.TIMER, fooPartTwo);
timer.start();
}
private function fooPartTwo(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, fooPartTwo);
timer = null;
// 3 seconds have passed, now do something more
}
}
You could also use another function inside your foo function and retain scope, so you don't need to pass variables around.
function foo(param1:int, param2:int, param3:int):void {
var x:int = 2; // you can use variables as you would normally
// do something here
var timer:Timer = new Timer(3000);
var afterWaiting:Function = function(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, afterWaiting);
timer = null;
// 3 seconds have passed, now do something more
// the scope is retained and you can still refer to the variables you
// used earlier
x += 2;
}
timer.addEventListener(TimerEvent.TIMER, afterWaiting);
timer.start();
}
For AS3 use Radu's answer.
For AS2 use the setInterval function like so:
var timer = setInterval(function, 3000, param1, param2);
function (param1, param2) {
// your function here
clearInterval(timer);
}
You can also use delayedCall, from TweenMax. IMHO, it's the sharpest way to do that if you are familiar to TweenMax family.
TweenMax.delayedCall(1, myFunction, ["param1", 2]);
function myFunction(param1:String, param2:Number):void
{
trace("called myFunction and passed params: " + param1 + ", " + param2);
}
In your case, using a anonymous function:
public function foo(param1, param2, param3) {
//do something here
trace("I gonna wait 3 seconds");
TweenMax.delayedCall(3, function()
{
trace("3 seconds have passed");
});
}
why you are doing some confused ways instead of doing the right way?
there is a method named:"setTimeout()";
setTimeout(myFunction,3000);
myFunction is the function you want to call after the period.and 3000 is the period you want to wait(as miliseconds).
you don't need to set then clear interval, or make a timer with one repeat count or do sth else with more trouble☺.
There is no Sleep in ActionScript. But there are other ways to achieve the same thing without having all your code in a single function and wait within that function a specific amount of time.
You can easily have your code in two functions and call the 2nd one after a specific timeout you set in your 1st function.
THIS IS NOT WITHIN ONE FUNCTION - ANSWERS: "How to wait for X seconds in AS2 & 3"
...without using setInterval or clearInterval.
The answers posted above are much faster and easier to use. I posted this here, just in case...
Sometimes you may not be able to use set/clearInterval or other methods based on development restrictions. Here is a way to make a delay happen without using those methods.
AS2 - If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
I have an onEnterFrame countdown timer in here as well, (demos stopping/switching timers).
If you want the delay/glow to be longer - increase the glowGameTime number. Change the names to fit your own needs and/or apply the logic differently.
var startTime:Number = 0;
var currentTime:Number = 0;
var mainTime:Number = 5;//"game" time on enter frame
var glowStartTime:Number = 0;
var glowCurrentTime:Number = 0;
var glowGameTime:Number = 1.8;//"delayed" time on press
btnGlowTest._visible = false;
this.onEnterFrame = TimerFunction;
startTime = getTimer();
function TimerFunction()
{
currentTime = getTimer();
var timeLeft:Number = mainTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up...3 bucks off");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
function glowTimerFunction()
{
glowCurrentTime = getTimer();
var glowTimeLeft:Number = glowGameTime - ((glowCurrentTime - glowStartTime)/1000);
glowTimeLeft = Math.floor(glowTimeLeft);
//trace("glowTimeleft = " + glowTimeLeft);
if(glowTimeLeft <= 0)
{
trace("TIME DELAY COMPLETE!");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
btnTest.onPress = function()
{
trace("onPress");
btnGlowTest._visible = true;
StopTime();
GlowTime();
}
function GlowTime()
{
trace("GlowTime Function");
this.onEnterFrame = glowTimerFunction;
glowStartTime = getTimer();
}
function StopTime()
{
trace(">>--StopTime--<<");
delete this.onEnterFrame;
}
AS3 - Below is the code from above setup to run in AS3. There are different ways to accomplish similar results, yet based on the project scope, these are the methods that were used in order to get things functioning properly.
If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
If you want the delay/glow to be longer - increase the GlowTimer:Timer number, (currently set to 950). Change the names to fit your own needs and/or apply the logic differently.
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
var startTime:Number = 0;
var currentTime:Number = 0;
var gameTime:Number = 4;//"game" time on enter frame
var GlowTimer:Timer = new Timer(950,0);//"delayed" time on press
btnGlowTest.visible = false;
GlowTimer.addEventListener(TimerEvent.TIMER, GlowTimeListener, false, 0, true);
btnTest.addEventListener(MouseEvent.MOUSE_DOWN, btnTestPressed, false, 0, true);
addEventListener(Event.ENTER_FRAME,TimerFunction, false, 0, true);
startTime = getTimer();
function TimerFunction(event:Event)
{
currentTime = getTimer();
var timeLeft:Number = gameTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up, 3 bucks off");
StopTime();
}
}
function GlowTimeListener (e:TimerEvent):void
{
trace("TIME DELAY COMPLETE!");
StopTime();
}
function btnTestPressed(e:MouseEvent)
{
trace("PRESSED");
removeEventListener(Event.ENTER_FRAME, TimerFunction);
btnGlowTest.visible = true;
GlowTimer.start();
}
function StopTime()
{
trace(">>--Stop Time--<<");
btnGlowTest.visible = false;//just for show
btnTest.visible = false;//just for show
GlowTimer.stop();
removeEventListener(TimerEvent.TIMER, GlowTimeListener);
removeEventListener(Event.ENTER_FRAME, TimerFunction);
}

how to execute js function with rhino and env.rhino.js ?

Scriptable envGlobals;
InputStreamReader envReader = new InputStreamReader(getClass()
.getResourceAsStream("env.rhino.js"));
// InputStreamReader jqueryReader = new InputStreamReader(getClass()
// .getResourceAsStream("jquery-1.6.2.js"));
try {
Context cx = ContextFactory.getGlobal().enterContext();
try {
Global global = new Global();
global.init(cx);
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_7);
envGlobals = cx.initStandardObjects(global);
try {
cx.evaluateReader(envGlobals, envReader,
"env.rhino.js", 1, null);
// cx.evaluateReader(envGlobals, jqueryReader,
// "jquery-1.6.2.js", 1, null);
} catch (IOException e) {
}
} finally {
Context.exit();
}
} finally {
try {
envReader.close();
} catch (IOException e) {
}
}
/**
* the above code nicely evaluates env.rhino.js and provides a scope
* object (envGlobals). Then for each script I want to evaluate
* against env.rhino.js's global scope:
*/
Context scriptContext = ContextFactory.getGlobal().enterContext();
try {
// Create a global scope for the dependency we're processing
// and assign our prototype to the environment globals
// (env.js defined globals, the console globals etc.). This
// then allows us to (a) not have to re-establish commonly
// used globals i.e. we can re-use them in our loop; and (b)
// any global assignments are guaranteed to have come from
// the dependency itself (which is what we're trying to
// determine here).
Scriptable globalScope = scriptContext.newObject(envGlobals);
globalScope.setPrototype(envGlobals);
globalScope.setParentScope(null);
scriptContext.setOptimizationLevel(-1);
scriptContext.setLanguageVersion(Context.VERSION_1_7);
try {
//scriptContext.evaluateString(globalScope, "window.location='http://www.amazon.com'", "location", 1, null);
scriptContext.evaluateString(globalScope, tree.toSource(), "script document", 1, null);
System.out.println(scriptContext.toString());
// TODO: Do something useful with the globals.
} finally {
Context.exit();
}
....
Function f = (Function)fObj;
Object result = f.call(scriptContext, globalScope, globalScope, params);
throught this format,i always get the Exception info:
Exception in thread "main" java.lang.NullPointerException
at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:849)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:164)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:426)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3178)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:162)
at org.sdc.food.parse.util.JavaScriptParser.getExecutableJS(JavaScriptParser.java:244)
at org.sdc.food.parse.util.JavaScriptParser.main(JavaScriptParser.java:349)
pls,someone help me!!
I have solved this. The reason is that the params passed to the called function is wrong.

Resources