从一个函数多次访问原子变量
Atomic Variables Accessed Multiple Times From One Function
我有以下代码:
header:
class Counter
{
public:
Conuter(const std::string& fileName);
boost::uint16_t getCounter();
private:
tbb::atomic<boost::uint32_t> counter;
std::string counterFileName;
};
cpp:
Counter::Counter(const std::string& fileName) : counter(), counterFileName(fileName)
{
std::string line;
std::ifstream counterFile (fileName.c_str());
if (counterFile.is_open())
{
getline (counterFile, line);
counterFile.close();
}
boost::uint32_t temp = std::stoul (line,nullptr,0);
counter = temp;
}
boost::uint32_t Counter::getCounter()
{
if (counter > 1000)
{
counter = 0;
}
assert( counter < 1000);
const boost::uint32_t ret = counter++;
if ((counter % 10) == 0)
{
// write the counter back to the file.
std::ofstream file (counterFileName.c_str());
if (file.is_open())
{
myfile << counter;
myfile.close();
}
}
return ret;
}
在其他地方假设我们有两个线程:
boost::thread t1(&Counter::getCounter, counter);
boost::thread t2(&Counter::getCounter, counter);
我的问题是关于原子变量的。由于 getCounter 函数每次调用最多可以访问计数器值 3 次,因此原子变量可以从一次调用更改为下一次调用。例如,如果对 if (counter > 1000) 的调用未能通过,是否有任何形式的保证断言也会通过?也许更具体地说,原子变量会一直阻塞到函数调用结束吗?或者只要值是read/written?我的第二个问题是,操作系统如何处理原子?就好像原子在完成之前不会导致函数阻塞一样,如果一个线程正在更新变量而另一个线程试图写出它会发生什么?很抱歉有很多问题,这是我第一次尝试无锁数据结构。
首先,即使在单线程应用程序中,
的序列
if (counter > 1000) ...
assert(counter < 1000)
计数器为 1000 时将失败。
其次,是的,原子变量可以在读取之间轻松更改。它的全部要点是单次读取是原子的,如果另一个线程在读取变量时恰好更新变量,你保证有一个正确的内存顺序读取(你也有一些关于算术的保证 - 你的增量保证增量)。但它没有说明下次阅读!
如果您需要锁定变量,您需要使用锁定机制,例如互斥锁。
我有以下代码:
header:
class Counter
{
public:
Conuter(const std::string& fileName);
boost::uint16_t getCounter();
private:
tbb::atomic<boost::uint32_t> counter;
std::string counterFileName;
};
cpp:
Counter::Counter(const std::string& fileName) : counter(), counterFileName(fileName)
{
std::string line;
std::ifstream counterFile (fileName.c_str());
if (counterFile.is_open())
{
getline (counterFile, line);
counterFile.close();
}
boost::uint32_t temp = std::stoul (line,nullptr,0);
counter = temp;
}
boost::uint32_t Counter::getCounter()
{
if (counter > 1000)
{
counter = 0;
}
assert( counter < 1000);
const boost::uint32_t ret = counter++;
if ((counter % 10) == 0)
{
// write the counter back to the file.
std::ofstream file (counterFileName.c_str());
if (file.is_open())
{
myfile << counter;
myfile.close();
}
}
return ret;
}
在其他地方假设我们有两个线程:
boost::thread t1(&Counter::getCounter, counter);
boost::thread t2(&Counter::getCounter, counter);
我的问题是关于原子变量的。由于 getCounter 函数每次调用最多可以访问计数器值 3 次,因此原子变量可以从一次调用更改为下一次调用。例如,如果对 if (counter > 1000) 的调用未能通过,是否有任何形式的保证断言也会通过?也许更具体地说,原子变量会一直阻塞到函数调用结束吗?或者只要值是read/written?我的第二个问题是,操作系统如何处理原子?就好像原子在完成之前不会导致函数阻塞一样,如果一个线程正在更新变量而另一个线程试图写出它会发生什么?很抱歉有很多问题,这是我第一次尝试无锁数据结构。
首先,即使在单线程应用程序中,
的序列if (counter > 1000) ...
assert(counter < 1000)
计数器为 1000 时将失败。
其次,是的,原子变量可以在读取之间轻松更改。它的全部要点是单次读取是原子的,如果另一个线程在读取变量时恰好更新变量,你保证有一个正确的内存顺序读取(你也有一些关于算术的保证 - 你的增量保证增量)。但它没有说明下次阅读!
如果您需要锁定变量,您需要使用锁定机制,例如互斥锁。