#!/usr/bin/env python from igraph import * from threading import Thread from time import sleep, time class DiameterCalculation(Thread): def __init__(self, graph): # Call superclass constructor Thread.__init__(self) # Mark it a daemon thread so Ctrl-C interrupts the calculation self.setDaemon(True) # Initialize progress counter self.progress = 0. self.result = None # Store the graph locally self.g = graph def run(self): n = self.g.vcount() max_distance = 0 for i in xrange(n): # Do some tedious calculation max_distance = max(max_distance, max(g.shortest_paths(i)[0])) # Update the progress counter self.progress = 100. * (i+1) / n # Let other threads run every now and then sleep(0.000001) # Return the result self.result = max_distance print "Generating graph..." g = Graph.Barabasi(5000) print "Starting worker thread..." worker_thread = DiameterCalculation(g) t1 = time() worker_thread.start() while worker_thread.isAlive(): worker_thread.join(0.1) print "Thread progress: %.2f%%" % worker_thread.progress print "Worker thread exited, result =", worker_thread.result print "Calculation took %.2fs" % (time() - t1)