Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Threads&Queques
#1
Can I implement the threads in this code, having queues too?
I have solved the problem with some sort of strings called threads, I haven't really used the properties of the
threads, and I haven't launched any process.

The statement:

Write a program that launches 3 threads with all 3 having
the purpose of writing or reading from the same file.
Threads prepare strings of different lengths (sizes) in a buffer and transfer the contents of the buffer into the common file while the strings are completed.

The request to write one of the threads should be signaled to the other 2 threads that must be interrupted to allow the file to be modified.
The program will display the character strings added by each of the threads in the file, followed by the thread name that created that.

my code here
import time
import random
import logging
import sys, os
import multiprocessing
from multiprocessing import Process, Queue, current_process, freeze_support
import sys, threading, logging, os
import datetime
from time import gmtime, strftime

#
# Function run by worker processes
#

def worker(input, output):
for func, args in iter(input.get, 'STOP'):
result = execute_function(func, args)
output.put(result)

#
# Function used to calculate result
#

def execute_function(func, args):
result = func(args)
return '%s says that %s %s = %s' % \
(current_process().name, func.__name__, args, result)

#
# Functions referenced by tasks
#

def utilisation():
print
"""
Le programme doit etre appelle avec 2 arguments:
python projet7.py ,
le fichier duquel on lit les chaines de caracters Nom_de_fichier.txt
(dans ce cas le nom de fichier est a.txt),
le fichier dans lequel on ecrit les threads(out.txt)
"""

def main(argv=None):
working_dir = os.path.dirname(os.path.abspath(__file__)) + os.path.sep
#Configurez le logging pour ecrire dans un fichier texte
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
filename=working_dir + 'process.log',
level=logging.INFO)
logging.info("Main start")

#Bucla principala
if argv is None:
argv = sys.argv

if len(argv) == 1:
utilisation()
return 0
else:
NUMBER_OF_PROCESSES = 4

thread01 = []
thread02 = []
thread03 = []

queue01 = Queue()
queue02 = Queue()
queue03 = Queue()

max01 = 9
max02 = 9
max03 = 9


print ( "Threads pour les chaines de caracteres:" )
print ( "\r\n" )


with open(working_dir + argv[1], 'r') as f:
for line in f:
from random import randint
thNumber = randint(1, 3)
line = line.strip('\r\n')
if thNumber == 1:
if len(line) > max01:
max01 = len(line)
queue01.put(line)
thread01.append(line)
elif thNumber == 2:
if len(line) > max02:
max02 = len(line)
queue02.put(line)
thread02.append(line)
elif thNumber == 3:
if len(line) > max03:
max03 = len(line)
queue03.put(line)
thread03.append(line)

print "Thread 01: "
print thread01

print "Thread 02: "
print thread02

print "Thread 03: "
print thread03

with open(working_dir+argv[2], 'w') as f:
f.write("Thread 01:\n"+ str(thread01)+"\n")
f.write("Thread 02:\n"+ str(thread02)+"\n")
f.write("Thread 03:\n"+ str(thread03)+"\n")

maxTh = max(len(thread01), len(thread02), len(thread03))
for i in range(0, maxTh):

len01 = len(thread01)

if len01 <= i:

thread01.append("---------")
queue01.put("---------")

newLen = max01 - 9
aux = thread01[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread01[i] = aux

elif len01 < max01:

newLen = max01 - len(thread01[i])
aux = thread01[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread01[i] = aux

len02 = len(thread02)

if len02 <= i:

thread02.append("---------")
queue02.put("---------")

newLen = max02 - 9
aux = thread02[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread02[i] = aux

elif len02 < max02:

newLen = max02 - len(thread02[i])
aux = thread02[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread02[i] = aux

len03 = len(thread03)

if len03 <= i:

thread03.append("---------")
queue03.put("---------")

newLen = max03 - 9
aux = thread03[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread03[i] = aux

elif len03 < max03:

newLen = max03 - len(thread03[i])
aux = thread03[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread03[i] = aux

print "| " + thread01[i] + " | " + thread02[i] + " | " + thread03[i] + " |"

f.write("| " + str(thread01[i]) + " | " + str(thread02[i]) + " | " + str(thread03[i]) + " |\r\n")

sp01 = ''
sp02 = ''
sp03 = ''

if 9 < max01:

max01 -= 9
while max01 > 0:
sp01 += " "
max01 -= 1

if 9 < max02:

max02 -= 9
while max02 > 0:
sp02 += " "
max02 -= 1

if 9 < max03:

max03 -= 9
while max03 > 0:
sp03 += " "
max03 -= 1

print "| Thread 01 " + sp01 + "| Thread 02 " + sp02 + "| Thread 03 " + sp03 + "|"
f.write("| Thread 01 " + sp01 + "| Thread 02 " + sp02 + "| Thread 03 " + sp03 + "|")

if __name__ == '__main__':
#freeze_support()
sys.exit(main())
Reply
#2
  • Please post your code between code tags see: BBCODE
  • To preserve indenting and remove formatting, paste code using shift-ctrl-v
Reply
#3
import time
import random
import logging
import sys, os
import multiprocessing
from multiprocessing import Process, Queue, current_process, freeze_support
import sys, threading, logging, os
import datetime
from time import gmtime, strftime

#
# Function run by worker processes
#

def worker(input, output):
for func, args in iter(input.get, 'STOP'):
result = execute_function(func, args)
output.put(result)

#
# Function used to calculate result
#

def execute_function(func, args):
result = func(args)
return '%s says that %s %s = %s' % \
(current_process().name, func.__name__, args, result)

#
# Functions referenced by tasks
#

def utilisation():
print 
"""
Le programme doit etre appelle avec 2 arguments:
python projet7.py ,
le fichier duquel on lit les chaines de caracters Nom_de_fichier.txt
(dans ce cas le nom de fichier est a.txt),
le fichier dans lequel on ecrit les threads(out.txt)
"""

def main(argv=None):
working_dir = os.path.dirname(os.path.abspath(__file__)) + os.path.sep
#Configurez le logging pour ecrire dans un fichier texte
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
filename=working_dir + 'process.log',
level=logging.INFO)
logging.info("Main start")

#Bucla principala
if argv is None:
argv = sys.argv

if len(argv) == 1:
utilisation()
return 0
else:
NUMBER_OF_PROCESSES = 4

thread01 = []
thread02 = []
thread03 = []

queue01 = Queue()
queue02 = Queue()
queue03 = Queue()

max01 = 9
max02 = 9
max03 = 9


print ( "Threads pour les chaines de caracteres:" )
print ( "\r\n" )


with open(working_dir + argv[1], 'r') as f:
for line in f:
from random import randint
thNumber = randint(1, 3)
line = line.strip('\r\n')
if thNumber == 1:
if len(line) > max01:
max01 = len(line)
queue01.put(line)
thread01.append(line)
elif thNumber == 2:
if len(line) > max02:
max02 = len(line)
queue02.put(line)
thread02.append(line)
elif thNumber == 3:
if len(line) > max03:
max03 = len(line)
queue03.put(line)
thread03.append(line)

print "Thread 01: "
print thread01

print "Thread 02: "
print thread02

print "Thread 03: "
print thread03

with open(working_dir+argv[2], 'w') as f:
f.write("Thread 01:\n"+ str(thread01)+"\n")
f.write("Thread 02:\n"+ str(thread02)+"\n")
f.write("Thread 03:\n"+ str(thread03)+"\n")

maxTh = max(len(thread01), len(thread02), len(thread03))
for i in range(0, maxTh):

len01 = len(thread01)

if len01 <= i:

thread01.append("---------")
queue01.put("---------")

newLen = max01 - 9
aux = thread01[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread01[i] = aux

elif len01 < max01:

newLen = max01 - len(thread01[i])
aux = thread01[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread01[i] = aux

len02 = len(thread02)

if len02 <= i:

thread02.append("---------")
queue02.put("---------")

newLen = max02 - 9
aux = thread02[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread02[i] = aux

elif len02 < max02:

newLen = max02 - len(thread02[i])
aux = thread02[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread02[i] = aux

len03 = len(thread03)

if len03 <= i:

thread03.append("---------")
queue03.put("---------")

newLen = max03 - 9
aux = thread03[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread03[i] = aux

elif len03 < max03:

newLen = max03 - len(thread03[i])
aux = thread03[i]
while newLen > 0:
aux = aux + " "
newLen -= 1
thread03[i] = aux

print "| " + thread01[i] + " | " + thread02[i] + " | " + thread03[i] + " |"

f.write("| " + str(thread01[i]) + " | " + str(thread02[i]) + " | " + str(thread03[i]) + " |\r\n")

sp01 = ''
sp02 = ''
sp03 = ''

if 9 < max01:

max01 -= 9
while max01 > 0:
sp01 += " "
max01 -= 1

if 9 < max02:

max02 -= 9
while max02 > 0:
sp02 += " "
max02 -= 1

if 9 < max03:

max03 -= 9
while max03 > 0:
sp03 += " "
max03 -= 1

print "| Thread 01 " + sp01 + "| Thread 02 " + sp02 + "| Thread 03 " + sp03 + "|"
f.write("| Thread 01 " + sp01 + "| Thread 02 " + sp02 + "| Thread 03 " + sp03 + "|")

if __name__ == '__main__':
#freeze_support()
sys.exit(main())
Reply
#4
I thread is not a string. It is an independent  process, one that runs independently of the main process, it is managed by a scheduler.
It returns to the main process when completed. The main process can wait for the thread to be done, but usually continues on with
whatever it's doing.
Reply
#5
Thank you
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020