开发者

How does one efficiently implement file region locking using grand central dispatch?

For my project, I am reading from and writing to a file from multiple threads, so I need to implement file locking. I have tried fcntl(), however it seems that function only works with locking between processes, not between threads. As such, I am looking for another solution. The solu开发者_如何学编程tion which I came up with (which is probably not the best) is to have a byte in each record in my file to indicate whether the record is locked, and I could then use a busy loop to read and check the byte.

So, I have two questions. First, what is the most efficient way to implement file region locking? Second, if I go with the busy loop approach, how can I optimize that with grand central dispatch? I was thinking that I could make all of the busy loops occur in blocks sent to dispatch_sync(). But I don't know whether or not that would even work efficiently.

Thanks.


How about Dispatch Semaphore? You can use Dispatch Semaphore to access exclusively resources. For instance, create Dispatch Semaphores for your file regions.

for (int i = 0; i < regions; ++i)
    sema_[i] = dispatch_semaphore_create(1);

And then, access resources with wait and signal.

dispatch_semaphore_wait(sema_[region], DISPATCH_TIME_FOREVER);
/* access the region */
dispatch_semaphore_signal(sema_[region]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜