Hi all,

could anyone please provide me a simple example of python threads?
I tried looking at the python cookbook, but I find it quite confusing with its mentioning of thread, threading etc (I am familiar with threads in C only)
All I want is: From my machine I need to execute scripts on two client machines. For this I want to use one thread per one client machine.
Within a single such thread I want to spawn a process that handles execution of python script on that particular client machine.
Any help would be highly appreciated!!

Regards,
Prashanth

When I started threading in Python, I had the exact same problem. It's quite difficult to find a very basic example of it. Let me try to give you one using the scenario you described.

I'm not quite sure how you are going to connect to the two client machines, so I'll leave that up to you. This is probably the most simple threading example you can have:

#!/usr/bin/python

import threading

class Client1Thread(threading.Thread):
    
    def __init__(self):
	threading.Thread.__init__(self)
	
    def run(self):
	print "Running the Client1 Thread"
	# Enter code here for client 1
	

class Client2Thread(threading.Thread):
    
    def __init__(self):
	threading.Thread.__init__(self)
	
    def run(self):
	print "Running the Client2 Thread"
	# Enter code here for client 2
	
threadOne = Client1Thread()
threadTwo = Client2Thread()

threadOne.start()
threadTwo.start()

If you need help with any of it, feel free to post back.

EDIT: There's a code snippet by a1eio that also shows a basic example of threading quite well. Link.

Hi,
Thanks for the reply.
The info has helped me to start the threads. Now i am trying to pass arguments to the thread.
My requirement is like this;
def myfoo(param1, param2):
-------
code
---------

myfoo(12, 15)

Basically I need to use the value of param1 within the thread function.

Regards,
Prashanth


When I started threading in Python, I had the exact same problem. It's quite difficult to find a very basic example of it. Let me try to give you one using the scenario you described.

I'm not quite sure how you are going to connect to the two client machines, so I'll leave that up to you. This is probably the most simple threading example you can have:

#!/usr/bin/python

import threading

class Client1Thread(threading.Thread):
    
    def __init__(self):
	threading.Thread.__init__(self)
	
    def run(self):
	print "Running the Client1 Thread"
	# Enter code here for client 1
	

class Client2Thread(threading.Thread):
    
    def __init__(self):
	threading.Thread.__init__(self)
	
    def run(self):
	print "Running the Client2 Thread"
	# Enter code here for client 2
	
threadOne = Client1Thread()
threadTwo = Client2Thread()

threadOne.start()
threadTwo.start()

If you need help with any of it, feel free to post back.

EDIT: There's a code snippet by a1eio that also shows a basic example of threading quite well. Link.

Try this:

#!/usr/bin/python

import threading

class Client1Thread(threading.Thread):
    
    def __init__(self, param1, param2):
	threading.Thread.__init__(self)
	self.param1 = param1
	self.param2 = param2
	
    def run(self):
	print "[Client1 Thread] The value of param1 is", self.param1
	print "[Client1 Thread] The value of param2 is", self.param2
	# Enter code here for client 1
	

class Client2Thread(threading.Thread):
    
    def __init__(self, param1, param2):
	threading.Thread.__init__(self)
	self.param1 = param1
	self.param2 = param2
	
    def run(self):
	print "[Client2 Thread] The value of param1 is", self.param1
	print "[Client2 Thread] The value of param2 is", self.param2
	# Enter code here for client 2
	
threadOne = Client1Thread("hello", "world")
threadTwo = Client2Thread(12, 15)

threadOne.start()
threadTwo.start()

Hi your reply has really helped me to implement the threads effectively. Utilizing your solutions i have now designed very effective client server architecture.
Many thanks for your solutions.

dear list i am new to python and write few basic programs in python now i want learn multithrading in pyhton , can anyone please provide me some link or guidance , how to go through it.
Warm Regards

dear list i am new to python and write few basic programs in python now i want learn multithrading in pyhton , can anyone please provide me some link or guidance , how to go through it.

Start by reading python module of the week: threading.

Start by reading python module of the week: threading.

Thanks alot Gribouillis, it helps me to undersatnd threading , but i think if i have to do some works with object oriented programming in pyhton, then how i could mannage to deal with multiple threads and FIFO.

Please forgive me if i asked something irrelevant.
Thank you

Dear Gribouillis and rest of the list,
Gribouillis as per your suggestion , i found it very useful for me, now i want to do some thing like,

i made two python files and both python files will gives some output and i want to print that output at the same time by using third python file by the help of multithreading, how could i do that,

please suggest something needful, and forgive me if i ask something irrelevant ,thank you in advance.

Warm regards

i made two python files and both python files will gives some output and i want to print that output at the same time by using third python file by the help of multithreading, how could i do that,

I found your question interesting, so I wrote a small class to do this, see if it can help you

#!/usr/bin/env python
# -*-coding: utf8-*-
# file printerthread.py
from __future__ import unicode_literals, print_function

import Queue
import sys
import threading

class PrintingThread(threading.Thread):
    def __init__(self, file = sys.stdout):
        threading.Thread.__init__(self)
        self.queue = Queue.Queue()
        self.cond = threading.Condition()
        self._shutdown = 0
        self.file = file

    def run(self):
        with self.cond:
            while True:
                self.cond.wait()
                if self._shutdown == 2:
                    self._abort()
                    return
                else:
                    self._print_queue()
                    if self._shutdown:
                        return

    def shutdown(self, value = 1):
        assert value in (1, 2)
        with self.cond:
            self._shutdown = value
            self.cond.notify()
        self.join()

    def _abort(self):
        try:
            while True:
                self.queue.get_nowait()
                self.queue.task_done()
        except Queue.Empty:
            return

    def _print_queue(self):
        try:
            while True:
                data = self.queue.get_nowait()
                self.file.write(data)
                self.queue.task_done()
        except Queue.Empty:
            return

    def print(self, *args, **kwd):
        sep = kwd.get('sep', ' ')
        end = kwd.get('end', '\n')
        s = sep.join(str(x) for x in args) + end
        self.write(s)

    def write(self, s):
        if len(s) == 0:
            return
        with self.cond:
            self.queue.put(s)
            self.cond.notify()

Here is a possible main program

#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import unicode_literals, print_function

from printerthread import PrintingThread
import time

def main():
    t = PrintingThread()
    t.start()
    for i in range(5):
        time.sleep(1)
        for j in range(3):
            t.print(time.time())
    t.shutdown()

if __name__ == "__main__":
    main()
#=======================================================

""" my output -->
1354444871.71
1354444871.71
1354444871.71
1354444872.71
1354444872.71
1354444872.71
1354444873.71
1354444873.71
1354444873.71
1354444874.71
1354444874.71
1354444874.71
1354444875.72
1354444875.72
1354444875.72
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.