Sahib Navlani
Sahib Navlani

Reputation: 80

A function not executing while threading

I created two modules which had some functions in them. I enclosed 2 functions in a single function in module1 and imported module1 in module2, The function often1 enclosed in compiler does'nt seem to execute.

MODULE 1

import time,thread

def class_often():
    while 1<2:
        time.sleep(5)
        print "Custom funtion not often runs."

def class_often1():
    while 1<2:
        time.sleep(2)
        print "Custom funtion often runs."

def compiler():
    class_often()
    class_often1()

MODULE2

import time,d,thread

def often():
    while 1<2:
        time.sleep(2)
        print "funtion not often runs."

def often1():
    while 1<2:
        time.sleep(2)
        print "Function often runs."

thread.start_new_thread(often,())
thread.start_new_thread(often1,())
thread.start_new_thread(d.compiler,())

Upvotes: 1

Views: 61

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

You start compiler in a thread but it calls class_often which blocks as it is an infinite loop so the second function cannot get called:

def compiler():
    class_often() # blocks
    class_often1()

You would need to thread.start_new_thread in d.complier also i.e:

def class_often():
    while True:
        time.sleep(5)
        print("Custom funtion not often runs.")


def class_often1():
    while True:
        time.sleep(2)
        print("Custom funtion often runs.")


def compiler():
    thread.start_new_thread(class_often,())
    class_often1()

Which after changing will give you output like:

funtion not often runs.
Custom funtion often runs.
Function often runs.
Custom funtion not often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
...........................

The threading lib is also recommended over the thread lib.

Upvotes: 2

Related Questions