Threads number

Threads creation and count

Postby almost_smart_blondie » Sun Jan 05, 2014 7:44 pm

I am very new in this, so having problems with threads.
Basically, the number of threads should be 3, since there are 3 clients connected. But I am doing something wrong here, please help!

nt@nt-VirtualBox:~/ts$ python ts.py
Socket created
Socket bind complete
waiting for connection... listening on port 8087
Connected with 127.0.0.1:33290
waiting for connection... listening on port 8087
Connected with 127.0.0.1:33291
n value 2
waiting for connection... listening on port 8087
Server is ready to receive
Number of threads active 1
number in handler
1
Connected with 127.0.0.1:33292
n value 3
waiting for connection... listening on port 8087
Server is ready to receive
Number of threads active 1
number in handler
1
Code: Select all
#…..this is part in main….
server_socket.listen(5) #maximum 5 connections
while 1:
          print 'waiting for connection... listening on port', port
         #wait to accept a connection - blocking call
         client, addr = server_socket.accept()
         #display client information
         n=n+1
         print 'Connected with ' + addr[0] + ':' + str(addr[1])
         if (n>1):
               print "n value", n
               thread.start_new_thread(handler, (client, addr))

Code: Select all
def handler(client, addr):
       #keep talking with the client
       print 'Server is ready to receive'
       print "Number of threads active", threading.activeCount()
       number = threading.activeCount()
       print "number in handler"
       print number
almost_smart_blondie
 
Posts: 3
Joined: Sun Jan 05, 2014 7:34 pm

Re: Threads number

Postby RainbowShibe » Sun Jan 05, 2014 9:34 pm

For multiple threads i would try overwriting the run() and __init__() functions in threading and making seperate functions that can be called in it,

Example:
Code: Select all
Import threading

Class MyThread (threading.Thread):
 #this is basically where you should store all of the values
 Def __init__(self, value1, value2):
  self.value1 = value1
  self.value2 = value2
 Def run(self):
  #this function doesnt really need anything other than self, although it depends
  #this is basically where you call every funcion that the thread would run
  Function(self.value1, self.value2)

Def Function(value, value2nd):
 If value == 1:
  Print("1 first thread")
 If value == 2:
  Print("2 second thread")
 If value2nd == 2:
  Print("2 first thread")
 If value2nd == 1:
  Print("1 second thread")
#define the the threads, with their arguments, for this it would be (value1, value2)
Thread1 = MyThread(1, 2)
Thread2 = MyThread(2, 1)
#calling the threads
Thread1.start()
Thread2.start()

The output should be something like (although i didnt test it):
Code: Select all
1 first thread
2 second thread
2 first thread
1 second thread
MLP:FIM <3
Image
User avatar
RainbowShibe
 
Posts: 10
Joined: Wed Jan 01, 2014 12:39 am
Location: Somewhere Over The Rainbow

Re: Threads number

Postby stranac » Sun Jan 05, 2014 9:39 pm

RainbowShibe wrote:although i didnt test it

That's pretty obvious...
import, class, def, if and print should all be lowercase.

Also, 1 space indents are really hard to see. The convention is to use 4 spaces for indenting.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 897
Joined: Thu Feb 07, 2013 3:42 pm

Re: fork, server can exit before children?

Postby almost_smart_blondie » Sun Jan 05, 2014 10:01 pm

I was able to create that thread program... and now I have the same program but I need to do it with fork now...having problem for waiting for children.
If a user press CTRL+C, the parent server needs to wait for children to finish and then can exit itself. Right now, it just exists right the way while a child is still connected.

Code: Select all
import os,sys
import socket
import time
import subprocess
from subprocess import Popen,PIPE,STDOUT,call
import signal

HOST = ''                             
PORT = 5449
socksize = 4096                           


conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.bind((HOST, PORT))
conn.listen(5)
print("Listening on TCP port %s" % PORT)

activeChildren = []
def reaper():   
                  
    while (activeChildren):
      pid,stst = os.waitpid(0, os.WNOHANG)   
      if not pid: break   
      activeChildren.remove (pid)      



def handler(connection):                   
    time.sleep(5)     
                             
    cmd = connection.recv(socksize)
    if "quit" in cmd: # TO DO
      print cmd
          
          
    elif "ls" in cmd:
   
                               print cmd
          client_port = connection.recv(5)
          emp_port= int (client_port)
      print 'emp_port from client is ', emp_port, 'connected on peer', connection.getpeername ()
          ip_host, c_port = connection.getpeername ()
          print ip_host
          print c_port
          server_data_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          server_data_socket.connect((ip_host, emp_port))
         
          pop = subprocess.Popen(['ls','-1'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,    stdin=subprocess.PIPE)                                                               
          datafile = pop.stdout.read()
          print datafile                               
          server_data_socket.send(datafile)
          server_data_socket.close()
    elif "get" in cmd:# TO DO
          print cmd
      
    elif "put" in cmd: # TO DO
          print cmd
              
    else:
      print cmd
      
    connection.close()
    os._exit(0)   
   

def accept():                               

   while True:   
                                           
           connection, address = conn.accept()
           print "welcome new client!"
      reaper()
      
           childPid = os.fork()                     
           if childPid==0:#child
         handler(connection)
         
         
           else:#parent
         activeChildren.append(childPid)
         
      
try:
   accept()
except KeyboardInterrupt:
   print "You press keyboard"
   #do I need to do something here?      
   connection.close()   
   sys.exit(0)
   
almost_smart_blondie
 
Posts: 3
Joined: Sun Jan 05, 2014 7:34 pm

Re: Threads number

Postby almost_smart_blondie » Thu Jan 16, 2014 2:54 am

looking for help here with fork now...the same program...

also tried to edit a couple of times.

I hope you guys can read it okey :geek:
almost_smart_blondie
 
Posts: 3
Joined: Sun Jan 05, 2014 7:34 pm


Return to Networking

Who is online

Users browsing this forum: No registered users and 1 guest