如何使用python3

时间:2017-06-07 01:40:44

标签: multithreading python-3.x

我想用python3在不同的线程中执行两个不同的命令,下面是我的代码:

import time
import threading
import os

class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result():
        return self.result


def sniffdata1():
    while 1:
        time.sleep(1)
        os.system("echo 2")

def sniffdata2():
        time.sleep(1)
        os.system("echo 1")

sniffThread1=MyThread(sniffdata1,())
sniffThread2=MyThread(sniffdata2,())
sniffThread1.start()
sniffThread2.start()
sniffThread1.join()
sniffThread2.join()

但我不能得到我的121212 ......,结果是1 2 2 2 2 2 2 2 ...(不多1),但总是回声2,有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

如果您想获得更多1,则应将while添加到sniffdata2()

def sniffdata2():
    while 1:
        time.sleep(1)
        os.system("echo 1")

但是如果你想一直得到12121212...,你应该使用这个代码:

import time
import threading
import os
flag2 = False;
flag1 = True;

class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        return self.result


def sniffdata1():
    global flag2, flag1
    while 1:
        if flag1:
            flag2 = False
            time.sleep(1)
            os.system("echo 1")
            flag1 = False
            flag2 = True

def sniffdata2():
    global flag2, flag1
    while 1:
        if flag2:
            flag1 = False
            time.sleep(1)
            os.system("echo 2")
            flag2 = False
            flag1 =True

sniffThread1=MyThread(sniffdata1,())
sniffThread2=MyThread(sniffdata2,())
sniffThread1.start()
sniffThread2.start()

答案 1 :(得分:0)

当我使用多进程处理它时,它可以工作,但我不清楚原因,下面是我的解决方案代码:

from multiprocessing import Process
import os
import time

def worker1():
  """test python multi process"""
  while 1:
      time.sleep(1)
      os.system("echo 1")
      #os.system("ping www.baidu.com")

def worker2():
  """test python multi process"""
  while 1:
      time.sleep(2)
      os.system("echo 2")
      #os.system("ping www.bing.com")

def main():
  jobs = []
  p1 = Process(target=worker1,args=())
  p2 = Process(target=worker2,args=())
  jobs.append(p1)
  jobs.append(p2)
  p1.start()
  p2.start()
  ##to avoid defunct process,you should call join()
  for j in jobs:
    j.join()

if __name__=='__main__':
  main()