Prime Multi Treading
Prime Multi Treading

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()



Leave a comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.