【发布时间】:2015-01-12 07:59:34
【问题描述】:
我只是 python 的初学者。我试图实现的是创建两个线程并在不同的线程中调用不同的函数。我在线程 1 中创建函数以执行一个函数 60 秒,线程 2 同时执行并等待主线程等待 70 秒。当线程一退出时,它也应该退出第二个线程,最后控制权应该来到主线程,再次调用线程一和线程二应该继续相同的过程。 我尝试使用下面的线程来实现它,但我无法做到
I have made a script in which i have started two thread named thread 1 and thread 2.
在线程 1 中,一个名为 func1 的函数将运行,而在线程 2 中,函数 2 将运行名为 func 2。 线程 1 将执行一个命令并等待 60 秒。 线程 2 将只运行到线程 1 运行。 之后,同样的过程在休息 80 秒后继续进行。
我是python的初学者。 请建议我做错了什么以及如何纠正它。
#!/usr/bin/python
import threading
import time
import subprocess
import datetime
import os
import thread
thread.start_new_thread( print_time, (None, None))
thread.start_new_thread( print_time1, (None, None))
command= "strace -o /root/Desktop/a.txt -c ./server"
final_dir = "/root/Desktop"
exitflag = 0
# Define a function for the thread
def print_time(*args):
os.chdir(final_dir)
print "IN first thread"
proc = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.wait(70)
exitflag=1
def print_time1(*args):
print "In second thread"
global exitflag
while exitflag:
thread.exit()
#proc = subprocess.Popen(command1,shell=True,stdout=subprocess.PIPE, sterr=subprocess.PIPE)
# Create two threads as follows
try:
while (1):
t1=threading.Thread(target=print_time)
t1.start()
t2=threading.Thread(target=print_time1)
t2=start()
time.sleep(80)
z = t1.isAlive()
z1 = t2.isAlive()
if z:
z.exit()
if z1:
z1.exit()
threading.Thread(target=print_time1).start()
threading.Thread(target=print_time1).start()
print "In try"
except:
print "Error: unable to start thread"
【问题讨论】:
-
请尝试想出一个更接近您的实际问题的标题,谢谢!
-
查看此链接。它将有助于 Python 线程。 tutorialspoint.com/python/python_multithreading.htm
标签: python linux multithreading