Reputation: 445
I have the following python code "ex.py" that is trying to execute two parallel threads of exact same functionality :
import thread
class PrtArg(object):
def print_name1(tname,*args):
cnt = 0
print "Inside print_name1"
while cnt < 10:
cnt += 1
print "%s : %s\n" % (tname, cnt)
def print_name(tname,*args):
cnt = 0
print "Inside print_name"
while cnt < 10:
cnt += 1
print "%s : %s\n" % (tname, cnt)
def m_prt(self,*args):
thread.start_new_thread(print_name, (args[0],))
thread.start_new_thread(print_name1, (args[1],))
And I have a test suite "example.robot" that has the following :
*** Settings ***
Documentation MultiThread Program
Library ex.PrtArg
*** Test Cases ***
Test title
[Documentation] MultiThread
[Tags] DEBUG
m_prt a b
*** Keywords
When I execute this, I get the following error:
==============================================================================
Ex :: MultiThread Program
==============================================================================
Test title :: MultiThread | FAIL |
NameError: global name 'print_name' is not defined
------------------------------------------------------------------------------
Ex :: MultiThread Program | FAIL |
1 critical test, 0 passed, 1 failed
1 test total, 0 passed, 1 failed
==============================================================================
Now, I came across this which says "threads should generally communicate with the framework only from the main thread". Isn't that what the above code does? I'm not even returning a value. Just printing to console. As expected, when I modify my "example.robot" to the following, it works fine:
*** Settings ***
Documentation MultiThread Program
Library example4.PrtArg
*** Test Cases ***
Test title
[Documentation] MultiThread
[Tags] DEBUG
print_name a
print_name1 b
*** Keywords ***
So, my questions are :
Upvotes: 0
Views: 11379
Reputation: 46
You should try declaring your method in static because they are in an instance of a class and the start_new_thread
doesn't take that.
So you code would look like that
import thread
class PrtArg(object):
@staticmethod
def print_name1(tname,*args):
cnt = 0
print "Inside print_name1"
while cnt < 10:
cnt += 1
print "%s : %s\n" % (tname, cnt)
@staticmethod
def print_name(tname,*args):
cnt = 0
print "Inside print_name"
while cnt < 10:
cnt += 1
print "%s : %s\n" % (tname, cnt)
def m_prt(self,*args):
thread.start_new_thread(PrtArg.print_name, (args[0],))
thread.start_new_thread(PrtArg.print_name1, (args[1],))
Upvotes: 3