是unique_ptr线程安全吗?下面的代码不可能两次打印相同的数字吗?是unique_ptr线程安全吗?
#include <memory>
#include <string>
#include <thread>
#include <cstdio>
using namespace std;
int main()
{
unique_ptr<int> work;
thread t1([&] {
while (true) {
const unique_ptr<int> localWork = move(work);
if (localWork)
printf("thread1: %d\n", *localWork);
this_thread::yield();
}
});
thread t2([&] {
while (true) {
const unique_ptr<int> localWork = move(work);
if (localWork)
printf("thread2: %d\n", *localWork);
this_thread::yield();
}
});
for (int i = 0; ; i++) {
work.reset(new int(i));
while (work)
this_thread::yield();
}
return 0;
}
“令人兴奋的是,当如果发生这种情况,它也将导致整的双重释放。”它可能*。它可能不会。它可能导致根本不释放该整数。它可能会导致两个移动的版本都有指针值的一半。它可以做各种事情。 – 2012-07-14 17:29:23
的确,我对这个架构做了一些假设,而这些架构并没有真正的保证。 – Useless 2012-07-14 19:05:26