1

I am trying to run a thread more than once and keep getting an error:

RuntimeError: threads can only be started once

I have tried reading up multithreading and implementing it in my code without any luck.

Here is the function I am threading:

def receive(q):
    host = ""
    port = 13000
    buf = 1024
    addr = (host,port)
    Sock = socket(AF_INET, SOCK_DGRAM)
    Sock.bind(addr)
    (data, addr) = Sock.recvfrom(buf)
    q.put(data)

Here is the code I want to run:

q = Queue.Queue()
r = threading.Thread(target=receive, args=(q,))

while True:
    r.start()
    if q.get() == "stop":
        print "Stopped"
        break
    print "Running program"

When the stop message gets sent, the program should break out of the while loop, but it does not run due to multithreading. The while loop should constantly print out Running program, until the stop message is sent.

The queue is used to receive the variable data from the receive function (which is the stop).

6
  • 1
    Might help: stackoverflow.com/questions/20745352/… Commented Dec 15, 2014 at 15:17
  • You are constantly calling r.start()? Because if no message is received, your q.get() will return None (or maybe it is a blocking function, not sure?) and your code will try to start the thread again, even though the first instance is still running. Commented Dec 15, 2014 at 15:19
  • @Lawrence I am trying to overcome this with either stopping the thread at the end of the while loop, or creating another thread instance, which I am unsure on how to do. Commented Dec 15, 2014 at 15:23
  • The threading module has no attribute named thread, so you should be getting an AttributeError from the threading.thread(target=receive, args=(q,)) statement. Commented Dec 15, 2014 at 17:36
  • @martineau Typo my bad, corrected with a captial thread with a captial T, Thread. This should return the RuntimeError. Commented Dec 15, 2014 at 17:41

2 Answers 2

1

Here is a working example (for python 2.7).

The program has two modes of operation:

  • with no arguments it runs the receive loop
  • with arguments it sends a datagram

Note how r.start() and r.terminate() are called outside of the while loop in client. Also, receive has a while True loop.

import sys
import socket
from multiprocessing import Process, Queue

UDP_ADDR = ("", 13000)

def send(m):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    sock.sendto(m, UDP_ADDR)

def receive(q):
    buf = 1024
    Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    Sock.bind(UDP_ADDR)
    while True:
      (data, addr) = Sock.recvfrom(buf)
      q.put(data)

def client():
  q = Queue()
  r = Process(target = receive, args=(q,))
  r.start()

  print "client loop started"
  while True:
      m = q.get()
      print "got:", m
      if m == "stop":
          break
  print "loop ended"

  r.terminate()

if __name__ == '__main__':
  args = sys.argv
  if len(args) > 1:
    send(args[1])
  else:
    client()
Sign up to request clarification or add additional context in comments.

4 Comments

This works fine. However, what if I were to receive multiple messages. So the first message that sends is start and then it loops to do something until stop is sent. I have modified your code slightly and added in what I have mentioned above: while True: m = q.get() print "got:", m while m == "start": print "started" z = q.get() if z == "stop": return @user5402
If you post it as another SO question I can answer it. This space is too small for a detailed answer.
You can view the new question here @user5402
This returns error: [Errno 98] Address already in use and does not work.. @user5402
-1

I think the problem is once the thread is started, calling thread.start() again throws the error.

Using a try block would might work as a simple fix:

while True:
    try:
      r.start()
    except Exception:  
#or except RunTimeError: 
      pass
    if q.get() == "stop":
        print "Stopped"
        break
    print "Running program"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.