I'm doing a program that should simulate file synchronization between two threads, but I do not know much about the python language. I've already created threads, lock methods, and files. However I can not make the run select a file at the source, use lock_read at the source, and lock_write at the destination.
Does anyone know how to do it? I've tried it in several ways ..
import sys, time
from threading import Semaphore, Thread
from pprint import pprint
from random import random, choice
from time import sleep
class RWLock:
def __init__(self):
self.m_rdcnt = Semaphore(1)
self.r = Semaphore(1)
self.w = Semaphore(1)
self.readcount = 0
def lock_read(self):
self.w.aquire()
self.m_rdcnt.acquire()
readcount+=1
if (readcount == 1):
self.r.acquire()
self.m_rdcnt.release()
self.m_rdcnt.acquire()
def unlock_read(self):
readcount-=1
if (readcount==0):
self.r.release()
self.m_rdcnt.release()
self.w.release()
def lock_write(self):
self.r.acquire()
self.w.acquire()
def unlock_write(self):
self.r.release()
self.w.release()
class Arquivos:
def __init__(self, nome, tamanho):
self.nome = nome
self.tamanho = tamanho
self.status = RWLock()
def __str__(self):
return "%s tamanho %d" % (self.nome, self.tamanho)
def __repr__(self): return self.__str__()
jekyll = []
jekyll.append(Arquivos("abc",10))
jekyll.append(Arquivos('dfg', 4))
jekyll.append(Arquivos('hij', 5))
jekyll.append(Arquivos('plo', 6))
jekyll.append(Arquivos('aad', 12))
jekyll.append(Arquivos('aes', 7))
jekyll.append(Arquivos('qas', 5))
hyde = []
hyde.append(Arquivos("abc",10))
hyde.append(Arquivos('dfg', 4))
hyde.append(Arquivos('hij', 5))
hyde.append(Arquivos('plo', 6))
hyde.append(Arquivos('aad', 12))
hyde.append(Arquivos('aes', 7))
hyde.append(Arquivos('qas', 5))
class SingThread(Thread):
def __init__(self, origem, destino):
Thread.__init__(self)
self.origem = origem
self.destino = destino
def run(self):
l=RWLock()
while 1:
#print('Bloqueando para Leitura %s' % (l))
l.lock_read()
#print('Desbloqueando para Leitura %s' % (l))
l.unlock_read()
#print('Bloqueando para Escrita %s' % (l))
l.lock_write()
#print('Desbloqueando para Escrita %s' % (l))
l.unlock_write()
t1 = SingThread(jekyll, hyde)
t2 = SingThread(hyde, jekyll)
t1.start()
t2.start()