b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

linux多线程 借shared_ptr实现copy-on-write (1)(3)

电脑杂谈  发布时间:2018-02-05 17:05:02  来源:网络整理

?? ?? ?? ?? 总而言之,一是要把copying放在临界区内,二是修改g_foos所指的 FooList要在copy之后进行,这样才安全。上面是自己对三种错误写法的个人观点,在此抛砖引玉了。linux多线程

??同样的,用相同的思路解决Linux多线程服务端编程—使用muduo C++网络库》的2.1.2节的MutualDeadLock例子。

?? ?? ?? ??具体代代码看github地址:

?? ?? ?? ?? ?? ?? ?? ??https://github.com/chenshuo/recipes/blob/master/thread/test/RequestInventory_test.cc

?? ?? ?? ??修改Inventory类的成员变量:

void add(Request* req)
??{
    ??muduo::MutexLockGuard lock(mutex_);
   ?? if (!requests_.unique())
   ?? {
       ?? requests_.reset(new RequestList(*requests_));
       ?? printf("Inventory::add() copy the whole list\n");
    ??}
    ??assert(requests_.unique());
    ??requests_->insert(req);
??}

void remove(Request* req) // __attribute__ ((noinline))
{
    muduo::MutexLockGuard lock(mutex_);
    if (!requests_.unique())
    {
      requests_.reset(new RequestList(*requests_));
      printf("Inventory::remove() copy the whole list\n");
    }
    assert(requests_.unique());
    requests_->erase(req);
}
?? 上面的方案仍然没解决Request对象析构的race conditon,解决方案需要用boost::enable_shared_from_this,Request继承它,还有Inventory类的add()和remove()这两个成员函数的参数,由原始指针改成shared_ptr智能指针。

具体代码看github地址 :https://github.com/chenshuo/recipes/blob/master/thread/test/RequestInventory_test2.cc

?? ?? ?? ?? 下面是继承boost::enable_shared_from_this的Request类的代码:


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-65219-3.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...