【问题标题】:Have the script achieved it was supposed to please check i am a beginner脚本是否实现了它应该请检查我是初学者
【发布时间】: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 linux multithreading


【解决方案1】:

我无法让示例运行,我需要将函数定义更改为

def print_time(*args)

和线程调用

thread.start_new_thread( print_time, (None, None))

那么你有很多问题

  1. 您当前没有等待在第二个线程中设置退出标志,它只是运行完成。
  2. 要在线程之间共享变量,您需要在线程中将它们声明为全局变量,否则您将获得一个局部变量。
  3. print_time1 函数中的thread.exit() 产生错误
  4. 您在问题描述和代码中的时间不匹配

所以,要解决 print_time1 的问题 1-3,请声明它(从末尾删除退出)

def print_time1(*args):
    global exitflag
    while exitflag == 0:  # wait for print_time 
        next
    # Do stuff when thread is finalizing

但是,请检查线程模块的文档 (https://docs.python.org/2/library/thread.html),“[...] 但是,您应该考虑改用高级线程模块。”

import threading
...

while(1):
    threading.Thread(target=print_time).start()
    threading.Thread(target=print_time1).start()
    time.sleep(80)

关于代码的最后一个要点是,在开始新的线程之前,您应该检查线程是否实际完成。现在每 80 秒启动两个新线程,这与旧线程是否运行完成无关。除非这是想要的行为,否则我会在 while 循环中添加一个检查。同样,当您使用它时,请将 try 子句移动到尽可能靠近可能引发异常的位置,即创建线程的位置。现在尝试封装while循环的方式不是很常见,而且imo不是很pythonic(增加了代码的复杂性)

【讨论】:

  • 你能分享你的邮件ID或在gunjanmehta08ATgmaildotcom发送测试邮件
  • 我也用最新的代码更新了问题,你可以检查一下
猜你喜欢
  • 1970-01-01
  • 2014-10-27
  • 1970-01-01
  • 2022-11-14
  • 2020-12-06
  • 2011-02-13
  • 2016-09-29
  • 1970-01-01
  • 2015-01-06
相关资源
最近更新 更多