I need to have multiple threads each read from the same socket or from
$*IN; however, there seems to be error because each is trying to read from the same source (I think). What is the best way to resolve this problem? Thanks !!
my $x = start { prompt("I am X: Enter x: "); }
my $y = start { prompt("I am Y: Enter y: "); }
await $x, $y;
say $x;
say $y;
And here are the errors:
I am X: Enter x: I am Y: Enter y: Tried to get the result of a broken Promise
in block <unit> at zz.pl line 4
Original exception:
Tried to read() from an IO handle outside its originating thread
in block at zz.pl line 1
Thanks !!
On the latest development snapshot of Rakudo, your code actually works without throwing any exception on my system...
However, it still immediately asks for both values (I am X: Enter x: I am Y: Enter y:).
To make the second prompt wait until the first one has completed, you could use a Lock:
#--- Main code ---
my $x = start { synchronized-prompt "I am X: Enter x: "; }
my $y = start { synchronized-prompt "I am Y: Enter y: "; }
await $x, $y;
say $x.result;
say $y.result;
#--- Helper routines ---
BEGIN my $prompt-lock = Lock.new;
sub synchronized-prompt ($message) {
$prompt-lock.protect: { prompt $message; }
}
The tricky part is that the lock needs to be initialized before the threads start using it concurrently. That's why I call Lock.new outside of the synchronized-prompt subroutine, in the mainline of the program. Instead of doing it at the top of the program, I use a BEGIN phaser so that I can place it next to the subroutine.
Related
A simple example
Print("This is a number {0}", 1) // results in 4
How can I print 1 2 3 in the same line?
I have tried
Print(1, 2, 3) // Does not work
The forloop also does not work.
The while loop below prints the elements but each in a separate line since we do not have control over the line feed character \n:
fn Main() -> i32 {
var a: [i32;3] = (1, 2, 3); // Define array containing the numbers 1,2,3
var i:i32 =0;
while(i<3){
Print("{0}", a[i]);
i= i+1;
}
return 0;
}
which results in
1
2
3
here is the code
How can I get 1 2 3?
Short explanation: Providing more than 2 arguments to Print is currently not supported, so is not including a line break.
Details
This is definitely something that will change in the future, as the language is in its early design phases. You can find the source for Print as an instrinsic (non-carbon native) here: https://github.com/carbon-language/carbon-lang/blob/trunk/explorer/interpreter/type_checker.cpp#L2297
case IntrinsicExpression::Intrinsic::Print:
// TODO: Remove Print special casing once we have variadics or
// overloads. Here, that's the name Print instead of __intrinsic_print
// in errors.
if (args.size() < 1 || args.size() > 2) {
return CompilationError(e->source_loc())
<< "Print takes 1 or 2 arguments, received " << args.size();
}
CARBON_RETURN_IF_ERROR(ExpectExactType(
e->source_loc(), "Print argument 0", arena_->New<StringType>(),
&args[0]->static_type(), impl_scope));
if (args.size() >= 2) {
CARBON_RETURN_IF_ERROR(ExpectExactType(
e->source_loc(), "Print argument 1", arena_->New<IntType>(),
&args[1]->static_type(), impl_scope));
}
If you look at the code you will also see that the type of input variable is limited to just integer types. It would be easy enough create a PR to manually add support for 2-3 if you want :)
I am using node js npm prompt-sync module. I have read that prompt-sync does not handle multiline inputs well, but none of my prompt inputs have \n characters. My expected output is to prompt, receive the input, then begin handling different prompts. This same code (similar to Main.js) works fine in Jest and produces the expected result. The observed result is that, upon answering anything, the line is printed again automatically with the given input without asking again. Then, there is no prompt given. But, upon typing more characters, it will repeat the prompt. It will also add previously repeated characters to the list of characters being returned.
Why is this happening and how can I produce the expected behavior?
UserInteraction.js:
class UserInteraction {
createPL(): {
console.log("Generating new PL: ");
let double_sided = prompt("DS? (Y/N): ").toLowerCase() === "y";
// other, different prompts...the expected output is a different prompt each time.
// use inputs for creating an object
}
createPLMap(): {
let cont = true;
let plMap = new Map();
while (cont) {
let pl= this.createPL();
// CODE REMOVED
}
return plMap;
}
Main.js:
const UserInteraction = require('./UserInteraction').UserInteraction;
async function MainAwait() {
let ui = new UserInteraction();
let pricelineSMap = ui.createPLMap();
}
MainAwait();
Shell file:
Main.sh:
node --trace-warnings ./js/Main.js
Output:
./Main.sh
Generating new PL:
DS? (Y/N): y
DS? (Y/N): y
y
DS? (Y/N): y
y
y
DS? (Y/N): y
y
y
y
DS? (Y/N): y
y
y
y
My questions is how to schedule running independent non-blocking functions every interval N.
My initial approach is to use go channels within a select statement to receive the values in a non-blocking manner and use time.Sleep(N) in each function to schedule the call.
In the code snippet below, this only for the first run; however, after the first call, it keeps calling computeY() repeatedly without respecting the time.Sleep() call.
package main
import (
"fmt"
"time"
)
var (
x string = ""
y string = ""
)
func computeY(c chan string) {
time.Sleep(10 * time.Second)
fmt.Println("I'm in Y")
y = "this is Y value"
c <- y
}
func computeX(c chan string) {
time.Sleep(1 * time.Second)
x = "this is X value"
c <- x
}
func main() {
xC := make(chan string)
yC := make(chan string)
for {
go computeX(xC)
go computeY(yC)
select {
case x := <-xC:
fmt.Println(fmt.Sprintf("X: %v, Y: %v", x, y))
case y := <-yC:
fmt.Println(fmt.Sprintf("X: %v, Y: %v", x, y))
}
}
}
You are calling both computeX and computeY every iteration of the loop.
Since computeX takes 1s, the for loop iterates once per second and an extra time when yC gets a value.
This means that you're running go computeY at t=0s, t=1s, t=2s, etc....
The first one terminates at t=10s, the second at t=11s, etc...
If you want to make sure you only schedule one computeX and computeY at a time, you need to change your main to something along the lines of:
go computeX(xC)
go computeY(yC)
for {
select {
case x = <-xC:
fmt.Printf("Finished computeX: X: %v, Y: %v\n", x, y)
go computeX(xC)
case y = <-yC:
fmt.Printf("Finished computeY: X: %v, Y: %v\n", x, y)
go computeY(yC)
}
}
A few other things to note about your code:
x and y are global and assigned in computeX and computeY
your channel reads shadow x and y
fmt.Println(fmt.Sprintf("...")) is just fmt.Printf("...\n")
you don't need to initialize strings to "", that's the default value
While #Marc's answer explains your code's problem and shows how to fix it, I will try to give you some patterns on scheduling functions.
Pattern 1: time.Ticker
A Ticker holds a channel that delivers `ticks' of a clock at intervals.
Example:
func Schedule(interval time.Duration,f func()) {
t:=time.NewTimer(interval)
go func() {
for {
<-t.C
f()
}
}()
}
Pattern 2: time.AfterFunc
AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method.
Example:
func Schedule(interval time.Duration,f func()) {
var wrap func()
wrap = func() {
f()
time.AfterFunc(wrap)
}
time.AfterFunc(f)
}
Pattern 1 is more readable and expressive while pattern 2 is more efficient on memory.
I am writing a program that calculates a Riemann sum based on user input. The program will split the function into 1000 rectangles (yes I know I haven't gotten that math in there yet) and sum them up and return the answer. I am using go routines to compute the 1000 rectangles but am getting an
fatal error: all go routines are asleep - deadlock!
What is the correct way to handle multiple go routines? I have been looking around and haven't seen an example that resembles my case? I'm new and want to adhere to standards. Here is my code (it is runnable if you'd like to see what a typical use case of this is - however it does break)
package main
import "fmt"
import "time"
//Data type to hold 'part' of function; ie. "4x^2"
type Pair struct {
coef, exp int
}
//Calculates the y-value of a 'part' of the function and writes this to the channel
func calc(c *chan float32, p Pair, x float32) {
val := x
//Raise our x value to the power, contained in 'p'
for i := 1; i < p.exp; i++ {
val = val * val
}
//Read existing answer from channel
ans := <-*c
//Write new value to the channel
*c <- float32(ans + (val * float32(p.coef)))
}
var c chan float32 //Channel
var m map[string]Pair //Map to hold function 'parts'
func main() {
c = make(chan float32, 1001) //Buffered at 1001
m = make(map[string]Pair)
var counter int
var temp_coef, temp_exp int
var check string
var up_bound, low_bound float32
var delta float32
counter = 1
check = "default"
//Loop through as long as we have no more function 'parts'
for check != "n" {
fmt.Print("Enter the coefficient for term ", counter, ": ")
fmt.Scanln(&temp_coef)
fmt.Print("Enter the exponent for term ", counter, ": ")
fmt.Scanln(&temp_exp)
fmt.Print("Do you have more terms to enter (y or n): ")
fmt.Scanln(&check)
fmt.Println("")
//Put data into our map
m[string(counter)] = Pair{temp_coef, temp_exp}
counter++
}
fmt.Print("Enter the lower bound: ")
fmt.Scanln(&low_bound)
fmt.Print("Enter the upper bound: ")
fmt.Scanln(&up_bound)
//Calculate the delta; ie. our x delta for the riemann sum
delta = (float32(up_bound) - float32(low_bound)) / float32(1000)
//Make our go routines here to add
for i := low_bound; i < up_bound; i = i + delta {
//'counter' is indicative of the number of function 'parts' we have
for j := 1; j < counter; j++ {
//Go routines made here
go calc(&c, m[string(j)], i)
}
}
//Wait for the go routines to finish
time.Sleep(5000 * time.Millisecond)
//Read the result?
ans := <-c
fmt.Print("Answer: ", ans)
}
It dead locks because both the calc() and the main() function reads from the channel before anyone gets to write to it.
So you will end up having every (non-main) go routine blocking at:
ans := <-*c
waiting for someone other go routine to enter a value into the channel. There fore none of them gets to the next line where they actually write to the channel. And the main() routine will block at:
ans := <-c
Everyone is waiting = deadlock
Using buffered channels
Your solution should have the calc() function only writing to the channel, while the main() could read from it in a for-range loop, suming up the values coming from the go-routines.
You will also need to add a way for main() to know when there will be no more values arriving, perhaps by using a sync.WaitGroup (maybe not the best, since main isn't suppose to wait but rather sum things up) or an ordinary counter.
Using shared memory
Sometimes it is not necessarily a channel you need. Having a shared value that you update with the sync/atomic package (atomic add doesn't work on floats) lock with a sync.Mutex works fine too.
I have a menu option with two options: add and substract. When I choose one it runs ok but the program closes. I would like to know how to make it go back to the menu after an operation ends to select another one
package main
import (
"fmt"
)
func main() {
var n1, n2, s, r float64
var op, ns int
fmt.Println("\n\tWelcome")
fmt.Println("Chose an option")
fmt.Println("1.-Add")
fmt.Println("2.-Substract")
fmt.Scan(&op)
if op == 1 {
fmt.Printf("\n\tAdd")
fmt.Printf("\nHow many numbers you add? ")
fmt.Scan(&ns)
if ns <= 1 {
fmt.Print("You can not add just a number")
} else {
for i := 0; i < ns; i++ {
fmt.Printf("\nType the number %d: ", i+1)
fmt.Scan(&n1)
s += n1
}
fmt.Println("\nThe sum is: ", s)
//How to return to the menu?
}
} else if op == 2 {
fmt.Printf("\n\tSubtraction")
fmt.Printf("\nType the first number: ")
fmt.Scan(&n1)
fmt.Printf("\nType the second number: ")
fmt.Scan(&n2)
r = n1 - n2
fmt.Println("\nSubstraction is: ", r)
}
}
Just wrap the whole thing in
for {
}
Use break to exit the loop or continue to go back to the top.
It's hard to tell exactly without seeing your code, but I may assume you should use operator for ;; {} and put inside your menu with the appropriate if/else statements.