Thread race conditions - multithreading

I have this algorithm that two threads run at the same time
n = 0
int tmp
do 10 times
tmp = n
n = tmp + 1
I know this can get 20, and 10 by each thread executing all the way to the end in sequence, and by one thread loading n into tmp, then the other finishing will result in 10.
I'm just not sure if this can get 2.

I would say that n will be >= 10 and <= 20, and that I really don't see how you could get anything < 10. But the whole thing is so wrong, I don't even know why I am answering :-)

Related

Game of life is running slow

I am trying to simulate n-dimensional game of life for first t=6 time steps. My Nim code is a straightforward port from Python and it works correctly but instead of the expected speedup, for n=4, t=6 it takes 2 seconds to run, which is order of magnitude slower than my CPython version. Why is my code so slow? What can I do to speed it up? I am compiling with -d:release and --opt:speed
I represent each point in space with a single 64bit integer.
That is, I map (x_0, x_1, ..., x_{n-1}) to sum x_i * 32^i. I can do that since I know that after 6 time steps each coordinate -15<=x_i<=15 so I have no overflow.
The rules are:
alive - has 2 or 3 alive neigbours: stays alive
- different number of them: becomes alive
dead - has 3 alive neighbours: becomes alive
- else: stays dead
Below is my code. The critical part is the proc nxt which gets set of active cells and outputs set of active cells next time step. This proc is called 6 times. The only thing I'm interested in is the number of alive cells.
I run the code on the following input:
.##...#.
.#.###..
..##.#.#
##...#.#
#..#...#
#..###..
.##.####
..#####.
Code:
import sets, tables, intsets, times, os, math
const DIM = 4
const ROUNDS = 6
const REG_SIZE = 5
const MAX_VAL = 2^(REG_SIZE-1)
var grid = initIntSet()
# Inits neighbours
var neigbours: seq[int]
proc initNeigbours(base,depth: int) =
if depth == 0:
if base != 0:
neigbours.add(base)
else:
initNeigbours(base*2*MAX_VAL-1, depth-1)
initNeigbours(base*2*MAX_VAL+0, depth-1)
initNeigbours(base*2*MAX_VAL+1, depth-1)
initNeigbours(0,DIM)
echo neigbours
# Calculates next iteration:
proc nxt(grid: IntSet): IntSet =
var counting: CountTable[int]
for x in grid:
for dx in neigbours:
counting.inc(x+dx)
for x, count in counting.pairs:
if count == 3 or (count == 2 and x in grid):
result.incl(x)
# Loads input
var row = 0
while true:
var line = stdin.readLine
if line == "":
break
for col in 0..<line.len:
if line[col] == '#':
grid.incl((row-MAX_VAL)*2*MAX_VAL + col-MAX_VAL)
inc row
# Run computation
let time = cpuTime()
for i in 1..ROUNDS:
grid = nxt(grid)
echo "Time taken: ", cpuTime() - time
echo "Result: ", grid.len
discard stdin.readLine
Your code runs in my computer in about 0.02:
Time taken: 0.020875947
Result: 2276
Time taken: 0.01853268
Result: 2276
Time taken: 0.021355269
Result: 2276
I changed the part where the input is read to this:
# Loads input
var row = 0
let input = open("input.txt")
for line in input.lines:
for i, col in line:
if col == '#':
grid.incl((row-MAX_VAL)*2*MAX_VAL + i-MAX_VAL)
inc row
input.close()
But it shouldn't impact the performance, it just looks better to my eyes. I compiled with:
nim c -d:danger script.nim
Using Nim 1.4.2. -d:danger is the flag for maximum speed before entering deeper waters.
But even compiling in debug mode:
$ nim c -r script.nim
Time taken: 0.07699487199999999
Result: 2276
Way faster than 2 seconds. There has to be other problem in your end. Sorry for the non-answer.

How do I make a program that asks the user for a limit and

I've got this code that asks the user for a limit, and then prints out the sequence of square numbers that are less than or equal to the limit provided.
n=int(input("Limit: "))
counter = 2
while counter <= n:
a = counter*counter
counter=a
print(a)
This is my current code, it's meant to work like this:
Max: 100
1
4
9
16
25
36
49
64
81
100
I'm stuck, how do I fix it? Thanks!
First off, you will want to start your counter variable at 1, otherwise you won't be able to get '1' as a square value.
In terms of printing the rest of the values, you will need to do 3 things:
Check if the square of counter is less than the limit.
If it is than the limit, print the result of counter * counter.
Increment counter by 1 <-- This is important!
Incrementing the counter by 1, is going to allow you to check every possible square that could exist below the specified limit. The following code provides a simple way to accomplish this that matches the pseudocode above:
n=int(input("Limit: "))
counter = 1
while counter <= n:
if counter * counter <= n:
print(counter * counter)
counter += 1
Let me know if you have any questions, I'm happy to clarify anything that still isn't making sense!
You're not actually calculating successive squares. You should be finding the square of counter, and then increasing counter by one
n=int(input("Limit: "))
counter = 1
sq = counter**2
while sq <= n:
print(sq)
counter += 1
sq = counter**2
Fun itertools solution:
from itertools import accumulate, count, takewhile
for i in takewhile(n.__gt__, accumulate(count(1, 2))):
print(i)

Making a variable a 'less than' value?

i'm really new to Python and am completely stuck
is there any way to make the less than value a variable
for example
x = int(input ("Input a value for x: "))
i = 1
while i < x:
x += i
i += 1
else:
print ("here is your new number:", x,)
whenever i use this, nothing happens
thanks for your help
It's not technically true to say that nothing happens, plenty is happening.
However, one thing that's not happening is the thing that generates the output (unless you enter a value less than or equal to one).
The while..else construct will only execute the else block if the while block did not do any iterations.
So, if you want output after the loop regardless of whether the loop body executes, get rid of the else and unindent the print.
The other thing that's not happening is the exit condition of the loop itself. If i starts out less than x (and they're both positive to start with), adding i to x then adding 1 to i will never give you a situation where i is not less than x.
Think about (for example):
x i Description
----- ----- -----------
3 1 Initial state
4 2 x += i; i += 1;
6 3 x += i; i += 1;
9 4 x += i; i += 1;
13 5 x += i; i += 1;
18 6 x += i; i += 1;
24 7 x += i; i += 1;
31 8 x += i; i += 1;
You can see that x is increasing at a faster rate than i, hence i < x will always be true.
How you fix that depends entirely on what you're trying to achieve. Since you have described your problem in terms of the code, your code matches perfectly your requirements. Hence, since you state it's not working as you expected, it appears your requirements may need some work :-)
I would suggest stating, in English, what you're trying to achieve here, and we can then suggest where your implementation has gone wrong.
What you wrote will result in an infinite loop if i < x in the beginning. So it will never reach the print statement that you hope it will. Plus, I also believe that you have to delete the else and indent the print statement.

while-loop to number 6174

I'am beginner in programming and have struggled for a while with one task.
Want to write a program wich finds out how many iterations is needed to arrive at the number 6174 from the specified number.
For example.: if I take number 2341 and sort it.
1) 4321-1234=3087
2) 8730-378=8352
3) 8532-2358=6174 (in this case it`s needed 3 iterations.)
And I have to use ,,while loop,, that it runs a code until it comes to number 6174 and stops.
I wrote a code:
n =input('write for nummbers ')
n=str(n)
i=0
i+=1 #"i" show how many times iteration happend.
large = "".join(sorted(n, reverse=True))
little = "".join(sorted(n,))
n = int(large) - int(little)
print(n, i)
Can you give mee some hint how I could run it with while loop.
# untested, all bugs are free ;)
n = input('write for nummbers ')
n = int(n) # you need n as a number
i=0
while n != 6174:
i += 1 #"i" show how many times iteration happened.
large = "".join(sorted(str(n), reverse=True))
little = "".join(sorted(str(n),))
n = int(large) - int(little)
print(n, i)

Prime number python nested loops

I am new to python and I am having some problems with this code that should print all the prime numbers that are smaller than 50 using nested loops.
Here is the code:
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
Its output is:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
So after 3, j should be 2 and i should be 4. Then it's not a prime number, so it goes back to the while loop.
And the process starts over. j and i should be incremented by one. So j should be 3 and i should be 5, 5 is prime, then it increments again to 6.
So j should still be 3 and i should be 6. But (3 <= (6/3)) <-- this is not true, so it goes to if statement and 3 which is j is bigger than 2 which is i/j, which means 6 should be prime.
But it's not. You can tell that by common sense. And I want to know what part I did wrong here. Did I miss any increments here? Thank you.
First of all, I would like to post the correct syntax for the code.
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
By writing the code like this, we are able to do several things. The first thing we are able to do is get a nice visual of what is inside of what, instead of assuming anything. The second thing that we are able to do is see what is being incremented where.
Now, let us approach what is going on inside of this code. The first to realize is that we are starting off with i=2. We are then initializing a while loop that is going to stop when i is greater than 50.
So, now we are inside of the first while loop, and the next thing we are doing is calling j. This variable is equal to 2, as we can see. Not only is it equal to 2, but every time we go down to the bottom of this FIRST WHILE LOOP THAT ENDS WHEN i >=50, we go back to the start and reinitialize j to be 2 again.
This means that j is never going to start out to be two, even though we are adding to j in the SECOND (NESTED) while loop.
Everything from here should make sense, if I understood your question right. The only thing that is weird about this code, in my opinion is the:
if not (i%j)
This seems a little odd, for it would be more clerical if it said:
if (i%j == 0):
break
If you have any other questions, please feel free to ask. And if you find this helpful, feel free to accept it as your answer :)
The indented code is as follows.
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j) :
print(i, " is prime")
i = i + 1
In your code, j is getting initialized to 2 with every increment of i.
See this snippet if not(i%j): break
If any j divides i, the if not(i%j) becomes true and the loop breaks but j <= (i/j) still holds else control wouldn't have entered this loop. So control skips print(i, " is prime")
So only way if(j > i/j) becomes true is when above loop never breaks. That would mean i didn't get any divisor, hence i is a prime.
I made this infinite prime number generator:
def primes_generator():
n = 1
while True:
for x in range(2, n):
if n % x == 0:
#not prime
break
else:
#prime
yield n
n+=1
you can use it like:
primes = primes_iterator()
for prime in primes:
print(i)

Resources