filelock icon indicating copy to clipboard operation
filelock copied to clipboard

filelock acquire stuck

Open zutb opened this issue 9 months ago • 3 comments

# coding=utf-8
import time
import asyncio
from threading import Thread
from filelock import FileLock


class TestObject(object):
    def __init__(self):
        self.file_lock = FileLock('/tmp/test_file.lock')
        print("file_lock acquire")
        self.file_lock.acquire()
        print("file_lock acquired")

    def run(self):
        time.sleep(5)
        print("file_lock release")
        self.file_lock.release()
        print("file_lock releasd")


async def test1():
    test_obj = TestObject()
    Thread(target=test_obj.run).start()


async def main():
    await test1()
    time.sleep(1)
    await test1()

if __name__ == '__main__':
    asyncio.run(main())
    time.sleep(10)

Image

zutb avatar Mar 06 '25 10:03 zutb

filelock >=3.11.0 This problem exists in versions later than 3.11. 0

zutb avatar Mar 06 '25 10:03 zutb

Passes in the CI. That being if you can replicate it within our test suite, then would be easier for someone to work on this.

gaborbernat avatar Mar 06 '25 19:03 gaborbernat

filelock >=3.11.0 This problem exists in versions later than 3.11. 0

v3.11.0 (2023-04-06) Make the lock thread local.

olutra avatar Mar 14 '25 23:03 olutra

Hello @zutb , your code acquires the lock in the main thread (in TestObject.__init__) but then creates a new thread to call TestObject.run which releases the lock. Since the lock is thread-local, it is not actually releasing the same lock that was acquired in the main thread. If you modify the first line of your __init__ method to be:

self.file_lock = FileLock('/tmp/test_file.lock', thread_local=False)

it should work as expected. Alternatively you could modify your code to acquire and release the lock in the same thread

mstockm avatar Oct 10 '25 18:10 mstockm