Multi Threading and still looking for Primes
[caption id="attachment_646" align="alignnone" width="300"]
Prime Multi Treading[/caption] Added some Multi Threading to my code to get full advantage of the dual core on my laptop:
import threading import time import inspect import sqlite3 import math
class Thread(threading.Thread): def __init__(self, t, *args): threading.Thread.__init__(self, target=t, args=args) self.start()
global variables
count = 0 lock = threading.Lock()
primeList = [] dbname='/home/roberto/primelist.db' table_name = 'primes' # name of the table to be created new_field = 'prime' # name of the column field_type = 'INTEGER' # column data type
def createDB():
Connecting to the database file
conn = sqlite3.connect(dbname)
c = conn.cursor()
try:
#c.execute('select prime from primes')
#primeList = c.fetchall()
for row in c.execute('select prime from primes order by prime'):
primeList.append(int(row\[0\]))
except:
# Creating a new SQLite table with 1 column
c.execute('CREATE TABLE {tn} ({nf} {ft})'\\
.format(tn=table\_name, nf=new\_field, ft=field\_type))
# Committing changes and closing the connection to the database file
conn.commit()
conn.close()
def add_prime(prime):
conn=sqlite3.connect(dbname, timeout = 30000)
curs=conn.cursor()
curs.execute("INSERT INTO primes values((?))", (prime,))
# commit the changes
conn.commit()
conn.close()
def isPrime(num):
prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(len(primeList)):
if ((num % primeList\[i\]) == 0 ) :
print(num,"is not a prime number")
#print(i,"times",num//i,"is",num)
break
if ((num / primeList\[i\]) < 2):
print(num,"is a prime number")
primeList.append(num)
add\_prime(num)
break
else:
#print(num,"is a prime number")
primeList.append(num)
add\_prime(num)
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
def incre(): global count
if len(primeList) == 0:
createDB()
if len(primeList) == 0:
count = 0
else:
count = primeList\[len(primeList)-1\]+1
caller = inspect.getouterframes(inspect.currentframe())\[1\]\[3\]
print "Inside %s()" % caller
print "Acquiring lock"
with lock:
print "Lock Acquired"
#print (count)
num = count
count += 1
isPrime(num)
def bye(): while count < math.pow(10, 101): incre()
def hello_there(): while count < math.pow(10, 101): incre()
def main():
hello = Thread(hello_there)
time.sleep(10)
goodbye = Thread(bye)
if __name__ == '__main__': main()