I am trying to learn the "threading" module. However, I am not sure I was able to create multiple threads.
import threading
import time
def somefunction():
for loop in range (10):
print "thread sleeps for 20 seconds"
time.sleep(20)
print "thread %d woke up"
counter = 0
while counter < 10:
threader = threading.Thread(target=somefunction())
counter = counter +1
When I run the following command, it only returns one NLWP.
ps axo pid,ppid,rss,vsz,nlwp,cmd | grep -i python
What am I doing wrong?
You have to use the reference in the parameter target to somefunction and not call the function.
import threading
import time
def somefunction():
for loop in range (10):
print "thread sleeps for 20 seconds"
time.sleep(20)
print "thread %d woke up"
for counter in range(10):
threader = threading.Thread(target=somefunction)
Related
I need some help with my code
I used to use exit() function in python but today I tried to use threading library
This my code:
import time
import threading
ts = time.time()
ts_after = ts + 5
def printit():
global ts_after
threading.Timer(1.0, printit).start()
ts1 = time.time()
if int(ts1) >= int(ts_after):
print("11")
exit()
else:
pass
printit()
it's work very well and print("11") also work but the exit() after the print doesn't work and keep printing 11
Using the cancel() method on the Timer instance seems to produce your desired behaviour:
import time
import threading
ts = time.time()
ts_after = ts + 5
def printit():
global ts_after
my_thread = threading.Timer(1.0, printit)
my_thread.start()
ts1 = time.time()
if int(ts1) >= int(ts_after):
print("11")
my_thread.cancel()
else:
pass
printit()
The cancel() method simply stops the Timer instance before it has begun. Note that it is probably a good idea to extend this code so that it can also quit Timer objects that have already started.
I created a code that shows a real time clock at the beginning (works by a loop and refreshing itself in every 1 sec using \r )
But I want to run the rest of the code while the clock is ticking (continuously). But this isn't going any further while the loop is running.
I think there is no need to write the code of the clock.
If you want to have a task running, while using another you can use multi-threading. This means you tell your processor two different tasks and it will be continued as long as you tell it to work. See here a post about multithreading and multiprocessing. You can use the thread function of python for this.
Here a small example:
import threading
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 10:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
def counter(threadName, number_of_counts, delay):
count=0
while count < number_of_counts:
print ("%s: %s" % ( threadName, count))
time.sleep(delay)
count +=1
# Create two threads as follows
threading.Thread(target=print_time, args=("Thread-1", 1, )).start()
threading.Thread(target=counter, args=("Thread-2", 100, 0.1,)).start()
for further information check the documentation. Note that thread has been renamed to _thread in python 3
I am new to python and threading. I am trying to run multiple threads at a time. Here is my basic code :
import threading
import time
threads = []
print "hello"
class myThread(threading.Thread):
def __init__(self,i):
threading.Thread.__init__(self)
print "i = ",i
for j in range(0,i):
print "j = ",j
time.sleep(5)
for i in range(1,4):
thread = myThread(i)
thread.start()
While 1 thread is waiting for time.sleep(5) i want another thread to start. In short, all the threads should run parallel.
You might have some misunderstandings on how to subclass threading.Thread, first of all __init__() method is roughly what represents a constructor in Python, basically it'll get executed every time you create an instance, so in your case when thread = myThread(i) executes, it'll block till the end of __init__().
Then you should move your activity into run(), so that when start() is called, the thread will start to run. For example:
import threading
import time
threads = []
print "hello"
class myThread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
def run(self):
print "i = ", self.i
for j in range(0, self.i):
print "j = ",j
time.sleep(5)
for i in range(1,4):
thread = myThread(i)
thread.start()
P.S. Because of the existence of GIL in CPython, you might not be able to fully take advantages of all your processors if the task is CPU-bound.
Here is an example on how you could use threading based on your code:
import threading
import time
threads = []
print "hello"
def doWork(i):
print "i = ",i
for j in range(0,i):
print "j = ",j
time.sleep(5)
for i in range(1,4):
thread = threading.Thread(target=doWork, args=(i,))
threads.append(thread)
thread.start()
# you need to wait for the threads to finish
for thread in threads:
thread.join()
print "Finished"
import threading
import subprocess
def obj_func(simid):
simid = simid
workingdir = './' +str (simid) # the working directory for the simulation
cmd = './run_delwaq.sh' # cmd is a bash commend to launch the external execution
subprocess.Popen(cmd, cwd=workingdir).wait()
def example_subprocess_files():
num_threads = 4
jobs = []
# Launch the threads and give them access to the objective function
for i in range(num_threads):
workertask = threading.Thread(target=obj_func(i))
jobs.append(workertask)
for j in jobs:
j.start()
for j in jobs:
j.join()
print('All the work finished!')
if __name__ == '__main__':
example_subprocess_files()
This one not works for my case that the task is not print but CPU-Intensive task. The thread are excluded in serial.
I want to write a code which execute a statement specified number of times per second,
Many of you might be familier about the term rate
Here i want rate to be 30 per second
say i want to execute a function 30 times per second for 60 seconds
means rate=30/sec duration=60sec
Can any one tell me is their any api available in python to do the same ?
The sched module is intended for exactly this:
from __future__ import division
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def schedule_it(frequency, duration, callable, *args):
no_of_events = int( duration / frequency )
priority = 1 # not used, lets you assign execution order to events scheduled for the same time
for i in xrange( no_of_events ):
delay = i * frequency
scheduler.enter( delay, priority, callable, args)
def printer(x):
print x
# execute printer 30 times a second for 60 seconds
schedule_it(1/30, 60, printer, 'hello')
scheduler.run()
For a threaded environment, the use of sched.scheduler can be replaced by threading.Timer:
from __future__ import division
import time
import threading
def schedule_it(frequency, duration, callable, *args, **kwargs):
no_of_events = int( duration / frequency )
for i in xrange( no_of_events ):
delay = i * frequency
threading.Timer(delay, callable, args=args, kwargs=kwargs).start()
def printer(x):
print x
schedule_it(5, 10, printer, 'hello')
Try using threading.Timer:
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
You can use time.time() to do what you want:
import time
def your_function():
# do something...
while True:
start = time.time() # gives current time in seconds since Jan 1, 1970 (in Unix)
your_function()
while True:
current_time = time.time()
if current_time - start >= 1.0/30.0:
break
This will make sure that the delay between calls of your_function is very close to 1/30 of a second, even if your_function takes some time to run.
There is another way: using Pythons built-in scheduling module, sched. I never used it, so I can't help you there, but have a look at it.
After some time spending i discovered how to do it well i used multiprocessing in python to achieve it
here's my solution
#!/usr/bin/env python
from multiprocessing import Process
import os
import time
import datetime
def sleeper(name, seconds):
time.sleep(seconds)
print "PNAME:- %s"%name
if __name__ == '__main__':
pros={}
processes=[]
i=0
time2=0
time1=datetime.datetime.now()
for sec in range(5):
flag=0
while flag!=1:
time2=datetime.datetime.now()
if (time2-time1).seconds==1:
time1=time2
flag=1
print "Executing Per second"
for no in range(5):
i+=1
pros[i] = Process(target=sleeper, args=("Thread-%d"%i, 1))
j=i-5
for no in range(5):
j+=1
pros[j].start()
j=i-5
for no in range(5):
j+=1
processes.append(pros[j])
for p in processes:
p.join()
this is my code :
import thread
k=0
b=0
def a(n):
i = 0
while i<n:
print i
i += 1
j = 5000
while k < 5000:
a(k)
k+=1
for n in range(2,5):
thread.start_new_thread(a,(j*n,))
and i want to Run three threads and a main thread,
the main thread print 1,2,3,4,5,....5000
and the thread1 print 5001,5002,5003,...10000
the thread2 print 10001,10002,10003,...15000
the thread3 print 15001,15002,15003,...20000
they are at the same time
so what can i do ,
thanks
You should use threading instead of thread, since it's easier to implement and it works in almost every case. Now your code will be like:
import threading
class PrintNumber(Thread):
def __init__(self, n):
self.n = n
def run(self):
for i in range(n, n+5000):
print i
# create your threads here
# use a cicle if needed
thread = PrintNumber(0) # first 5000 numbers
thread.start()
thread = PrintNumber(5000) # next 5000
thread.start()
Coded from mind and have not tested it, should be working anyway