Skip to content

Instantly share code, notes, and snippets.

@SalvaJ
Created February 4, 2014 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SalvaJ/8803736 to your computer and use it in GitHub Desktop.
Save SalvaJ/8803736 to your computer and use it in GitHub Desktop.
Prueba de colisión en el uso de fichero por hilos concurrentes.
#!/bin/env python3
# -*- coding: UTF-8 -*-
# Prueba de programacion con threads para evaluar los conflictos en acceso a ficheros.
import threading, time
# Se crea una subclase de Thread
class MiThread(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
# Overrides el metodo de clase run() para definir el hilo nuevo y lo que hará
def run(self):
print ("I'm thread number: ", self.num)
for i in range(1, 50):
linea = ', '.join(["Thread", str(self.num), "Event", str(i), "\n"])
print(linea)
myFile.write(linea)
# fichero con el resultado
myFile = open('pruebaThreads.txt', mode='w')
print ("I'm the principal thread.")
t = MiThread(1) # se crea un objeto de la subclase Thread
t.start() # metodo start() llama a al hilo
print("I'm the principal thread, too.")
t = MiThread(2) # se crea otro hilo de la misma subclase
t.start()
print("I'm the principal thread, too.")
for h in range(3, 6): # se crean otros 3 hilos más
t = MiThread(h)
t.start()
print("I'm the principal thread, too.")
for j in range(1, 100):
otra_linea = ", ".join(["Main", str(j), str(t.isAlive()), "\n"])
print(otra_linea)
myFile.write(otra_linea)
t.join() # metodo join() para esperar a que termine el hilo (puede
# pasarse como parámetro los segundos a esperar).
@SalvaJ
Copy link
Author

SalvaJ commented Feb 4, 2014

Con 5 hilos no colisionan en el acceso al fichero en escritura.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment