【发布时间】:2018-04-09 17:27:52
【问题描述】:
我正在 python 中实现多线程代码。此示例每 2 秒打印一条消息。与 Windows 10 中 Pycharm 的结果相比,Ubuntu 中终端的输出不合逻辑。我认为 time 模块应该在两种环境中都可以工作。我不知道为什么它在 Linux 中不起作用。
另外,有没有其他类似time的模块可以使用?
感谢您的帮助
代码:
from threading import Thread
from time import sleep
from time import clock as clk
## To create a thread in Python you'll want to make your class work as a thread.
## For this, you should subclass your class from the Thread class
s2 = 0
class Book(Thread):
def __init__(self):
Thread.__init__(self)
self.message = ("Hello Parallel Python!!\n")
def print_message(self):
print (self.message)
##The run method prints the message
def run(self):
print ("Thread Starting")
x=0
while (x < 10):
self.print_message()
sleep(2)
print "Time is : ", clk()
x += 1
print ("Thread Ended\n")
s2 = clk()
print "2st s2 is: ", s2
#start the main process
print ("Process Started")
# create an instance of the HelloWorld class
hello = Book()
# print the message...starting the thread
s1 = clk()
hello.start()
#end the main process
print ("Process Ended\n")
print "1st s2 is: ", s2
在 Windows 10 中使用 Pycharm 的输出是:
在 Ubuntu 16.04 LTS 中使用 gedit 的输出是:
【问题讨论】:
标签: python multithreading python-2.7 time ubuntu-16.04