Python多线程编程的输出格式问题?
迷茫
迷茫 2017-04-17 16:36:38
0
4
690

今天在学习多线程编程,由于多个线程是同时启动的,所以输出也出现在了同一行,怎样才能换行输出呢?
输出结果是这样的:

*** MULTIPLE THREADS
startingstartingstarting   fibfacsum   at:at:at:   Tue Dec 08 22:30:43 2015Tue Dec 08 22:30:43 2015Tue Dec 08 22:30:43 2015


facsum  finished at:finished at:  Tue Dec 08 22:30:44 2015Tue Dec 08 22:30:44 2015

我想要的结果是这样的:

starting  fib    at: Sat Nov 22 09:51:39 2014

starting  fac    at:Sat Nov 22 09:51:39 2014

starting  sum   at:Sat Nov 22 09:51:39 2014

那我应该怎样做呢?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(4)
大家讲道理

First of all, thank you for your answers. However, these methods are still not clear to me, a Python beginner.
I solved this problem using other methods.
I thought that the switching between threads is an alternating loop in which one thread executes a few sentences and the other thread executes a few sentences again, and one sentence will not be interrupted.
The original mistake was that I wrote the output statement in this form:

print 'starting', funcs[i].__name__, 'at:',\
    ctime()

In fact, in Python’s view, this is not a statement, but the sum of several statements:

print 'starting',
print funcs[i].__name__,
print 'at:',
print ctime()

In this case, the threads will interrupt each other's output, so I changed the output statement and replaced it with this:

print 'starting %s at: %s\n' % (funcs[i].__name__, ctime()),

In this case, the output will be normal.

阿神

Add a lock to the output statement.

迷茫

logging

小葫芦

Each thread puts the content that needs to be output into Queue(), and specifically starts a thread to read data from Queue() and output it to the screen.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!