returning error code from open acc routine directive - gpu

I am porting a CPU code to GPU with OPENACC,
the routine returns exit code
int myFunction()
{
// so stuff
// it has a check for division by zero
int returnVal=SUCCESS;
if(fabs(a)<1e-14)
{
returnVal=1;
}
return(returnVal);
}
adding the
#pragma acc routine seq
int myFunction()
{
// so stuff
// it has a check for division by zero
int returnVal=SUCCESS;
if(fabs(a)<1e-14)
{
returnVal=1;
}
return(returnVal);
}
will give the following error,
call to cuStreamSynchronize returned error 719: Launch failed (often invalid pointer dereference)
call to cuMemFreeHost returned error 719: Launch failed (often invalid pointer dereference)
Primary job terminated normally, but 1 process returned
a non-zero exit code.. Per user-direction, the job has been aborted.
If I eliminate the return by changing it to void, it works fine,
what is the correct way of doing this ?
I do understand the race condition, given the fact that this is called inside a loop, should I privatize the return value and then perform a reduction on it?

Related

Declare val without initialization in function

class Solution {
val message: String //error : val must be initialized or abstract
message = "love" //error : val cannot be reassigned
}
I understand what's happening in here - val cannot be reassigned.
So when I need val but can not initialize it i used to use by lazy
class Solution {
fun love(){
val message : String
message = "love" //this works
message = "hate" //this is error "val cannot be reassigned"
}
}
Here I can delcare val without initialization and later write codemessage = "love".what's happening here?
#deHaar noticed correctly that only var (mutable variable) is appropriate in your case.
The error you get is absolutely correct and expected.
what's happening here?
When you declare a read-only variable without initializing it you have to make sure that each execution path will have a value in this read-only variable. It means that Kotlin makes sure if your read-only variable was or was not initialized in every place it is used and raises errors if the variable is used inappropriately.
Here you have only one execution path as there are no when or if statements that can split execution into several possible paths.
class Solution {
fun love(){
val message : String
message = "love" // Kotlin knows that `message` was not yet initialized
message = "hate" // Kotlin knows that `message` was yet initialized! It does not allow to modify the value.
}
}
Here is what Kotlin documentation says:
... it is also possible (but discouraged) to split the declaration and the initial assignment, and even to initialize in multiple places based on some condition. You can only read the variable at a point where the compiler can prove that every possible execution path will have initialized it. If you're creating a read-only variable in this way, you must also ensure that every possible execution path assigns to it exactly once.
Example of an execution path
Using when or if statement you create two or more execution paths. Execution paths can be presented as a graph, I'll use #number as a node number. Example:
class Solution {
fun love(){
// #1
val message : String
if (System.currentTimeMillisec() % 2 == 0) {
message = "Not empty"
// #2
}
if (message.isEmpty) { // Error! Message could be not initialized at this point!
println("Empty message")
// #3
}
}
}
Looking at this example, that does not compile, we can calculate at least 3 execution paths.
#1 (none of the if statements was entered. All conditions are false)
#1 -> #2
#1 -> #3
Kotlin can calculate these paths and check if the message variable is initialized in every path it is used. As we can see, as soon as you reach the evaluation of the second if statement (in case of first and third paths) your program will crash because the message has no value. It has no address in memory and a computer which runs this program does not know how to get a value from an address that does not exist.
Now, let's modify this code to make it work:
class Solution {
fun love(){
// #1
val message : String
if (System.currentTimeMillisec() % 2 == 0) {
message = "Not empty"
// #2
} else {
message = ""
// #3
}
if (message.isEmpty) { // Error! Message could be not initialized at this point!
println("Empty message")
// #4
}
}
}
Execution paths:
#1 -> #2
#1 -> #3 -> #4
In this example, Kotlin is sure that the message read-only variable is initialized because there is a 100% chance that one of node 2 or node 3 will be executed. Right after the line where the message gets its initial value (initialized) Kotlin treats this variable as a read-only variable with a value.
Questions are welcome. I will try to simplify this answer.

Understanding how waitpid works with signals

Consider the following Pseudo-C code:
static int G = 0;
void alrm_handler(int signo) {
G = 1;
}
void son() {
struct sched_param param;
param.sched_priority = 50;
sched_setscheduler(getpid(),SCHED_FIFO, &param);
kill(getppid(), SIG_ALRM);
sched_yield();
printf("A\n");
while(1);
exit(0);
}
int main() {
signal(SIG_ALRM, alrm_handler);
int son_pid = fork();
if(son_pid==0)
son();
waitpid(son_pid);
printf("B\n");
return 0;
}
It's from an exam in OS. The question is as follows:
In multi cores CPU what would be printed?
The answers is that we can't know because it could be A and then B or B and then A. I don't understand why. If parent is waiting for the son with waitpid and the son sends signal SIG_ALRM which invokes the alrm_handler function for the parent, the parent will finish executing the function and then return to waiting the son until he will finish running, no? So it should be A and then B.
According to POSIX it is undefined whether system calls are restarted after a signal handler set by signal is called.
System V and the Linux signal system call do not restart system calls.
BSD and by default GLibc, do restart system calls.
If System V signal is used waitpid can return as soon the signal has been sent, allowing the letters to be printed in any order. If standard output is a pipe or regular file only B will be output as the child is in a infinite loop
With BSD signal only A will be printed as waitpid does not return due to the infinite loop in the child. If standard output is a pipe or regular file only nothing will be output.

Why is the last line not executed by this code?

int main()
{
alarm(2);
printf("still going\n");
while (1);
printf("should this line be executed?\n");
}
I understand that alarm() will interrupt the execution, set the alarm to go off and hand it back. Why does the last line not get executed?
It's not printed because while(1); is an infinite loop. So, in the absence of the alarm() call, that would run forever.
However, the signal generated two seconds after you call alarm() will cause the program to terminate if you're not catching it.
What it won't do is cause just the loop to exit and the program to carry on. It will shut the program down, quick smart.
If you do catch the signal but your catching function just returns, it will end up back inside the infinite loop.
For more detail on those two cases, examine the following code:
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int fired = 0;
void handler (int sig) {
fired = 1;
}
int main (void) {
// signal (SIGALRM, handler);
alarm (2);
printf ("Starting.\n");
while (1) {
if (fired) {
fired = 0;
printf ("Alarm fired.\n");
alarm (2);
}
}
printf ("You will never see this.\n");
return 0;
}
If you run that code, it will print out the Starting message, run for about two seconds, then exit without printing anything else. That's because you're not catching the signal so the default action is to just terminate the process.
If you uncomment the call to signal() (disregard for now that it's considered preferable to use sigaction() instead), you'll see the Starting message, followed by a Alarm fired message about every two seconds.
That's because you are catching the signal but, on exit, it returns to inside the infinite loop.
while (1);
This is an infinite loop. Execution will never go beyond this.

How do I exit a Rust program early from outside the main function?

I am in the process of writing a bash clone in Rust. I need to have my program exit when the user types exit. In previous iterations of my program, before I added more complicated features, I used return to get out of the loop that was prompting the user for input. This logic is now in a function, because of the way I am implementing built in shell functions, so when I return it just jumps out of the function back into the control loop, instead of short-circuiting the control loop and ending the program.
I realize that I could probably return a boolean when the user types exit and exit the loop, but I would like to at least know if Rust has a way to terminate programs early, similar to Java's System.exit(), as this is useful for certain types of programs.
Rust 1.0 stable
std::process::exit() does exactly that - it terminates the program with the specified exit code:
use std::process;
fn main() {
for i in 0..10 {
if i == 5 {
process::exit(1);
}
println!("{}", i);
}
}
This function causes the program to terminate immediately, without unwinding and running destructors, so it should be used sparingly.
Alternative (not recommended) solution
You can use C API directly. Add libc = "0.2" to Cargo.toml, and:
fn main() {
for i in 0..10 {
if i == 5 {
unsafe { libc::exit(1); }
}
println!("{}", i);
}
}
Calling C functions cannot be verified by the Rust compiler, so this requires the unsafe block. Resources used by the program will not be freed properly. This may cause problems such as hanging sockets.
As far as I understand, the proper way to exit from the program is to terminate all threads somehow, then the process will exit automatically.
panic!("Oh no something bad has happened!")
Example:
if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); }
In older documentation, you will see this as fail!("Oh no something bad here has happened.")
For some reason, this macro was changed from fail to panic. Panic is the way to fail, if you must.
[edit] I am sorry. It looks like you should be testing input for the string "exit," which would depend on how you are taking input (by line or by args). Then you can have the program break out of the loop on the condition that the exit is detected.
Example:
loop {
if exit_found { break }
else {
// your thing, which also looks for exit_found
}
}

Objective-C Blocks, Recursion Fails

Sup guys,
I'm trying to do a function that calls itself but by putting everything on one block,
As you can see, the following function is intended to be called an indefinite amount of times (until arcrandom returns a number lower than 50) and you should expect as an output a variable number of "RUNNING" messages, depending on chance.
void (^_test_closure)(void) = ^ {
NSLog(#"RUNNING");
if(arc4random() % 100 > 50) {
_test_closure();
}
};
_test_closure();
However, when running it, I get an EXC_BAD_ACCESS error and the reason I've found is that when the code tries to calls _test_closure inside of the closure it basically points to nowhere.
Does anyone know how to make the above code work?
You have to declare your block itself as a block variable:
__block void (^_test_closure)();
_test_closure = ^{
NSLog(#"Running...");
if ((arc4random() % 100) > 50) {
_test_closure();
}
}
_test_closure();
Recursion and blocks is tricky. Because a block captures all variables passed in, the variable _test_closure is not initialized yet (and clang should give you a warning:
Block pointer variable '_test_closure' is uninitialized when captured by block
).
There are several ways you can get around this, but the most obvious & simplest is to just make the block itself a __block variable (what #H2CO3 said). This allows the block to be weak-linked almost, so that when you call it again, it is properly initialized.
Another option you have is making the block a global or static, like this:
// outside of 'main', thus being a global variable
void (^blockRecurse)(int) = ^(int level) {
if (level < 0)
return;
NSLog(#"Level: %i", level);
blockRecurse(--level);
};
int main()
{
#autoreleasepool {
blockRecurse(10);
}
}
This means it's not being captured by the block, but instead it's referencing the global / static variable, which can be changed by all code equally.
It works with XCode 5 - no warnings, no retain cycles:
typedef void(^blockT)();
blockT block1;
blockT __block block1recursive;
block1recursive = block1 = ^(){
block1recursive();
};
block1();