Synchronization of threads in python

Asked

Viewed 552 times

2

I am making a program that should simulate the synchronization of files between two threads, however, I do not know much the python language. I have already created the threads, lock methods and files. But I can’t run select a file at source, use lock_read at source, and lock_write at destination.

Does anyone know how to do it? I’ve tried 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()
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.