delica
delica

Reputation: 1727

Basic threading with one background worker and other thread

I'm very much a beginner in both python and programming. Trying to get multithreading work but haven't managed so far. Grateful for any help or tips.

from threading import Thread
import time
import requests

class crawler:

    def get_urls(self):
        while True:
            #r = self.s.get('http:\\someurl')
            time.sleep(1)
            print 'Thread 1'

    def thread_test(self):
        while True:
            print 'Thread 2'
            time.sleep(1)

crawl = crawler()

if __name__ == '__main__':
    Thread(target=crawl.get_urls()).start()
    Thread(target=crawl.thread_test()).start()

Upvotes: 0

Views: 661

Answers (1)

Abass Sesay
Abass Sesay

Reputation: 961

It has been a while since i have done thread programming in python but I remembered that you will have to call .join() on each thread or else the main thread will exit before your spawn thread get a chance to execute.

T1 = Thread(target=crawl.get_urls()).start()
T2 = Thread(target=crawl.thread_test()).start()
T1.join()
T2.join()

should do the trick

edit I just looked into python threading library the issue is that target is expecting a callable object. when you call target=crawl.get_urls() the method was being evaluated rather than passing the method.

from threading import Thread

import time import requests

class crawler:

def get_urls(self):
    while True:
        #r = self.s.get('http:\\someurl')
        time.sleep(1)
        print 'Thread 1'

def thread_test(self):
    while True:
        print 'Thread 2'
        time.sleep(1)

crawl = crawler()

if __name__ == '__main__':
    Thread(target=crawl.get_urls).start()
    Thread(target=crawl.thread_test).start()

ref: https://docs.python.org/3/library/threading.html#threading.Thread

Upvotes: 1

Related Questions