OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "rlz/lib/recursive_cross_process_lock_posix.h" | |
6 | |
7 #include <sys/file.h> | |
8 #include <sys/types.h> | |
9 #include <sys/stat.h> | |
10 #include <fcntl.h> | |
11 | |
12 #include "base/file_path.h" | |
13 #include "base/logging.h" | |
14 #include "base/posix/eintr_wrapper.h" | |
15 | |
16 namespace rlz_lib { | |
17 | |
18 bool RecursiveCrossProcessLock::TryGetCrossProcessLock( | |
19 const FilePath& lock_filename) { | |
20 bool just_got_lock = false; | |
21 | |
22 // Emulate a recursive mutex with a non-recursive one. | |
23 if (pthread_mutex_trylock(&recursive_lock_) == EBUSY) { | |
24 if (pthread_equal(pthread_self(), locking_thread_) == 0) { | |
25 // Some other thread has the lock, wait for it. | |
26 pthread_mutex_lock(&recursive_lock_); | |
27 CHECK(locking_thread_ == 0); | |
28 just_got_lock = true; | |
29 } | |
30 } else { | |
31 just_got_lock = true; | |
32 } | |
33 | |
34 locking_thread_ = pthread_self(); | |
35 | |
36 // Try to acquire file lock. | |
37 if (just_got_lock) { | |
38 const int kMaxTimeoutMS = 5000; // Matches Windows. | |
39 const int kSleepPerTryMS = 200; | |
40 | |
41 CHECK(file_lock_ == -1); | |
42 file_lock_ = open(lock_filename.value().c_str(), O_RDWR | O_CREAT, 0666); | |
43 if (file_lock_ == -1) { | |
44 perror("open"); | |
45 return false; | |
46 } | |
47 | |
48 int flock_result = -1; | |
49 int elapsed_ms = 0; | |
50 while ((flock_result = | |
51 HANDLE_EINTR(flock(file_lock_, LOCK_EX | LOCK_NB))) == -1 && | |
52 errno == EWOULDBLOCK && | |
53 elapsed_ms < kMaxTimeoutMS) { | |
54 usleep(kSleepPerTryMS * 1000); | |
55 elapsed_ms += kSleepPerTryMS; | |
56 } | |
57 | |
58 if (flock_result == -1) { | |
59 perror("flock"); | |
60 ignore_result(HANDLE_EINTR(close(file_lock_))); | |
61 file_lock_ = -1; | |
62 return false; | |
63 } | |
64 return true; | |
65 } else { | |
66 return file_lock_ != -1; | |
Roger Tawa OOO till Jul 10th
2012/11/26 19:16:51
why not a DCHECK as well? Under what normal situa
Ivan Korotkov
2012/11/27 11:37:25
I think the point of this line was that if the top
| |
67 } | |
68 } | |
69 | |
70 void RecursiveCrossProcessLock::ReleaseLock() { | |
71 if (file_lock_ != -1) { | |
72 ignore_result(HANDLE_EINTR(flock(file_lock_, LOCK_UN))); | |
73 ignore_result(HANDLE_EINTR(close(file_lock_))); | |
74 file_lock_ = -1; | |
75 } | |
76 | |
77 locking_thread_ = 0; | |
78 pthread_mutex_unlock(&recursive_lock_); | |
79 } | |
80 | |
81 } // namespace rlz_lib | |
OLD | NEW |