stop multiple threads from acessing a variable

129 views Asked by At

I'm using flask for a web application, it was all going well till I had to deal with multiple requests( I am using threaded=true)

My problem is if I get two parallel requests then flask will create two threads and they will try to create a file with the same name (I have to use epoch time for file name)

Even if i put lock on the file as soon as the the lock is released the other thread will try to create a file with the same name (as both the threads will have the same name value

from flask import Flask
import time

app = Flask(__name__)

@app.route('/start', methods=['GET'])
    try:
        # how can i lock a flask's thread from accessing this part so that two threads can't have files with the same name
        name = str(int(time.time()))
        with open(name,'w') as FileObj:
            FileObj.write('Hey')
    except:
        abort(500)

    return "created a file"

def main():
    """
    Main entry point into program execution

    PARAMETERS: none
    """
    app.run(host='0.0.0.0',threaded=True)

main()

does the flask thread work with threading.Lock(), if i put a lock around the name will the both parallel threads have different values?

PS: i know i could use random name for the files and avoid this problem, but i kind of have to use epoch time that's a pain

0

There are 0 answers