【发布时间】:2021-04-28 08:47:59
【问题描述】:
我能够使用信号量值设置为 1 的信号量获得以下多线程代码的顺序输出。但是,现在不是同时运行 3 个进程,而是一次只运行一个线程,这是预期的。有没有一种方法可以同时运行三个线程并获得顺序输出?
from datetime import datetime
import getpass
import os
import sys
import time
import re
import json
from random import random
import threading
from io import StringIO
from time import gmtime, strftime
from pprint import pprint
from threading import *
screen_lock = Semaphore(value=1)
#------------------------------------------------------------------------------
def config_worker(port):
if port == 'a':
screen_lock.acquire()
print('PASS : Tunnel1 is UP from router 1')
print('PASS : Tunnel2 is UP from router 1')
print('PASS : Tunnel3 is UP from router 1')
screen_lock.release()
if port == 'b':
screen_lock.acquire()
print('PASS : Tunnel1 is UP from router 2')
print('PASS : Tunnel2 is UP from router 2')
print('PASS : Tunnel3 is UP from router 2')
screen_lock.release()
if port == 'c':
screen_lock.acquire()
print('PASS : Tunnel1 is UP from router 3')
print('PASS : Tunnel2 is UP from router 3')
print('PASS : Tunnel3 is UP from router 3')
screen_lock.release()
return
def connect():
config_threads_list = []
devices = ['a','b','c']
for ports in devices:
port = ports
print ('Creating thread for: ', ports)
config_threads_list.append(threading.Thread(target=config_worker, args=(port)))
print ('\n---- Begin get config threading ----\n')
for config_thread in config_threads_list:
config_thread.start()
for config_thread in config_threads_list:
config_thread.join()
connect()
使用信号量输出。输出是正确的,但一次只有一个线程在运行,这是预期的。如何运行所有线程并打印顺序输出?
---- Begin get config threading ----
PASS : Tunnel1 is UP from router 1
PASS : Tunnel2 is UP from router 1
PASS : Tunnel3 is UP from router 1
PASS : Tunnel1 is UP from router 2
PASS : Tunnel2 is UP from router 2
PASS : Tunnel3 is UP from router 2
PASS : Tunnel1 is UP from router 3
PASS : Tunnel2 is UP from router 3
PASS : Tunnel3 is UP from router 3
【问题讨论】:
-
各位,任何建议都会有所帮助。如果可以的话,请告诉我同样的情况
-
线程实际上并没有在同时的意义上“并发”运行 - 基本上线程只有在有原因时才会切换 - 通常基于 i/o,但我相信可以使用例如time.sleep(0) 让线程让出,如果有一个线程可以运行,Python 会运行另一个线程。如果您删除锁定并在每个打印语句后添加
time.sleep(0),您可能会看到这种情况发生。但是以控制线程切换为目标是矛盾的——如果你认为你需要完全控制线程执行的顺序,那么你可能不应该使用线程,写顺序。 -
更正 - 不要使用 0,使用例如
time.sleep(0.0001’)见stackoverflow.com/questions/787803/… -
hi barny 还有什么好主意
标签: python multithreading