Problem mit boost::interprocess::file_lock unter Linux
-
Folgender Code
#include <boost/interprocess/sync/file_lock.hpp> #include <iostream> #include <fstream> int main() { std::ofstream file("test.lock"); boost::interprocess::file_lock flock("test.lock"); std::cout << flock.try_lock(); std::cout << flock.try_lock() << std::endl; }
liefert bei mir unter Windows
10
unter Linux allerdings
11
. Das heißt es wirkt immer so, als wäre die Datei nicht gelockt, sollte sie aber nach einem Aufruf von try_lock, oder?
-
//!Effects: The calling thread tries to acquire exclusive ownership of the mutex
//! without waiting. If no other thread has exclusive, or sharable
//! ownership of the mutex this succeeds.
//!Returns: If it can acquire exclusive ownership immediately returns true.
//! If it has to wait, returns false.
//!Throws: interprocess_exception on errorprobiers mal von einem andere thread, ist es dann wie erwartet?
-
Leider auch mit
#include <boost/interprocess/sync/file_lock.hpp> #include <iostream> #include <fstream> #include <thread> int main() { std::ofstream file("test.lock"); auto f = []() { boost::interprocess::file_lock flock("test.lock"); std::cout << flock.try_lock() << std::endl; }; std::thread t1(f); std::thread t2(f); t1.join(); t2.join(); }
dasselbe Ergebnis (unter Windows 10, unter Linux 11).
-
Bau nach dem lock halt mal ein sleep ein, wenn du pech hast ist der erste Thread schon durch und hat den lock wieder freigegeben bevor der zweite lockt.
-
Auch folgendes gerade probiert:
#include <boost/interprocess/sync/file_lock.hpp> #include <iostream> #include <fstream> #include <thread> int main() { std::ofstream file("test.lock"); auto f = []() { boost::interprocess::file_lock flock("test.lock"); std::cout << flock.try_lock() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); }; std::thread t1(f); std::this_thread::sleep_for(std::chrono::milliseconds(500)); std::thread t2(f); t1.join(); t2.join(); }
Selbes Ergebnis ...
-
file_lock ist nicht threadsicher.
<a href= schrieb:
file_lock">A file lock can't guarantee synchronization between threads of the same process so just use file locks to synchronize threads from different processes.
-
Ahh, danke. Das heißt bisher war es einfach nur Glück, dass es unter Windows funktioniert?
Ich sollte dann
std::mutex
als Ersatz verwenden, richtig?
-
Mit 2 Threads muss die Ausgabe 11 sein, und das ist es bei mir unter Linux auch.
int main() { std::ofstream file("test.lock"); std::mutex m; auto f = [&m]() { std::lock_guard<std::mutex> g(m); boost::interprocess::file_lock flock("test.lock"); std::cout << flock.try_lock() << std::endl; // der Destruktor gibt den lock wieder frei. }; std::thread t1(f); std::thread t2(f); t1.join(); t2.join(); }