0

I am going to use threading in my Python application. Assume I want to run worker() function in a thread using below codes in main.py file:

def threadcalling():

        t = threading.Thread(target=worker())
        threads.append(t)
        t.start()

and my worker function in work.py file is such as this:

def worker():
    """thread worker function"""
    print 'Worker'
    return

My question: If the worker() function is in the same .py file which I am calling that, every thing is ok, But if the worker() function is in a another .py file which I have imported that in my main script using import command, I got this error:

<type 'exceptions.ValueError'>
Stateless
  • 293
  • 2
  • 4
  • 18
  • 1
    Please post your [**complete**](https://stackoverflow.com/help/mcve) code. Also, why do you want to manage threads manually? What's wrong with a [`ThreadPool`](http://stackoverflow.com/a/3386632/35070) or [`ThreadPoolExecutor`](https://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor)? – phihag May 06 '17 at 07:17
  • It is generally acceptable to use a function imported from another module, so it is a problem with your particular implementation. We can't say what that is without some demonstration code. If you want return values, a queue may be a good option. Consider `multiprocessing.pool.ThreadPool` which does most of the work for you. – tdelaney May 06 '17 at 07:20
  • @phihag and tdelaney, The problem was that my worker function is a method of a class in the separate file which I have not mentioned staticmethod keywork for that. Right now which I mentioned staticmethod keywork for worker function, every thing is ok! Do you have any idea about that? I am not very expert in python threading yet. – Stateless May 06 '17 at 07:42
  • @phihag, I do agree with you. Managing threads manually is not a very good idea and I think I must learn how to use ThreadPool or ThreadPoolExecutor. – Stateless May 06 '17 at 07:47

1 Answers1

1

For me, this works:

dede@i5:~> cat bb.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import threading
from cc import *

threads=[]
t = threading.Thread(target=worker)
threads.append(t)
t.start()

dede@i5:~> cat cc.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def worker():
    """thread worker function"""
    print 'Worker'
    return

dede@i5:~> python bb.py

Worker

For returning values from your worker(), use a global variable (with a lock) or a queue.

See: https://docs.python.org/2/library/threading.html

and: https://docs.python.org/2/library/queue.html#module-Queue

dede
  • 706
  • 9
  • 19