I am able to get sequential output for below multithreading code using semaphore with semaphore value set to 1. However instead of 3 processes running concurrently now there is just one thread running at a time which is expected. Is there a way where i can run three threads concurrently and also get sequential output as well?
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()
output with semaphore. output is correct but only one thread is running at a time which is expected. How to run all threads and print sequential output as well?
---- 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