我有一个多线程应用程序,使用静态方法写入设置xml文件.我想避免文件同时更新两次(导致访问/写入异常).
我怎么做?
这不起作用:
namespace Program
{
public class Settings
{
private static void SetSettingsValue (string settings, string value)
{
// make this thread safe to avoid writing to a locked settings xml file
lock (typeof(Settings))
{
//write data to xml file
}
}
}
}
Run Code Online (Sandbox Code Playgroud) 假设我有一个多线程C++程序,它以函数调用的形式处理请求handleRequest(string key).每次调用都handleRequest发生在一个单独的线程中,并且存在任意大量的可能值key.
我想要以下行为:
handleRequest(key)在具有相同值时被序列化key.handleRequest可能的主体看起来像这样:
void handleRequest(string key) {
KeyLock lock(key);
// Handle the request.
}
Run Code Online (Sandbox Code Playgroud)
问题:如何实现KeyLock以获得所需的行为?
一个天真的实现可能会像这样开始:
KeyLock::KeyLock(string key) {
global_lock->Lock();
internal_lock_ = global_key_map[key];
if (internal_lock_ == NULL) {
internal_lock_ = new Lock();
global_key_map[key] = internal_lock_;
}
global_lock->Unlock();
internal_lock_->Lock();
}
KeyLock::~KeyLock() {
internal_lock_->Unlock();
// Remove internal_lock_ from global_key_map iff no other threads are waiting for it.
}
Run Code Online (Sandbox Code Playgroud)
...但是,这需要在每个请求的开头和结尾处进行全局锁定,并为每个请求创建单独的Lock对象.如果调用之间的争用很高handleRequest,那可能不是问题,但如果争用率很低,则可能会产生大量开销.