[英]Lock a vector with a mutex - Boost
我正在为路由器编写代码,我想在接收器线程上接收到一个数据包后,将该数据包(目前为“ unsigned char *”类型)存储在向量中。 我有两个链接到两个不同接口的接收器线程,并且接收器线程仅应在另一个线程尚未访问该向量的情况下存储接收到的数据包。
除了两个接收线程之外,我还有一个主线程处理数据包和两个发送线程,每个接口一个。 总线程数为5。为防止在不同线程写入或读取向量时出现麻烦,我听说了一个互斥锁,据称该互斥锁应将向量锁定到其他(在这种情况下)线程,直到有问题的线程之后从向量读取或写入完成。
我想知道的是如何将其处理为代码。 一些例子将不胜感激。 我对C ++,Boost和Raw Sockets都很陌生。 最重要的是,我还不太喜欢在C ++中使用不同的类。 我非常了解它们在Java和C#中的工作方式,但是我发现C ++非常不同(由于头文件)。 我将所有代码都放在一个巨大的主类中,这可能不是很好的编码样式,但是现在它就是这样工作的。
我应该创建一个用于处理此向量的类(.h和.cpp文件)还是应该在我的巨型主类中实现它,如果是的话,我将为一些简单的示例感到高兴。 以下是我希望程序如何工作的示例。 我已经有了RecvThread,并且能够打印出数据包的MAC Hdr。
void RecvThread()
{
//receive a packet
while(true)
{
//get lock status from vector
if(vector is locked)
{
usleep(10000);
}
else
{
//lock vector
//save packet in vector
//unlock vector
}
}
}
void SendThread()
{
while(true)
{
//get lock status from vector
if(vector is locked)
{
usleep(10000);
}
else
{
//lock vector
//get packet from vector
//unlock vector
}
}
//send the packet
}
void MainThread()
{
while(true)
{
if(recv vector is empty)
{
usleep(10000);
}
else if(recv vector is locked)
{
usleep(10000);
}
else
{
//lock recv vector
//get packet in front of queue
//unlock recv vector
//process packet (update different fields)
//get packet interface (either 1 or 2)
if(send vector (matching interface) is locked)
{
usleep(10000);
}
else
{
//lock send vector (matching interface)
//save packet to send vector (matching interface)
//unlock send vector (matching interface)
}
}
}
}
int main()
{
//create Recv vector
//create Send vector 1 and 2 (one for each interface)
//create and join RecvThread 1 and 2
//create and join SendThread 1 and 2
//create and join MainThread
}
希望这能给您这个想法。 没有测试,因为它显然是不完整的:)关键是boost::lock_guard<boost::mutex> lock(mx_);
因为该行一次只能由一个线程执行。 实际上发生的事情是,例如线程A调用了此函数,因为它是第一个到达该线程的线程boost::lock_guard<boost::mutex> lock(mx_);
立即返回,线程可以进入临界区(锁定后的代码段)。 基本上是boost::lock_guard<boost::mutex> lock(mx_);
仅在关键部分内没有其他线程时返回。 如果关键部分已经被另一个线程访问,则boost::lock_guard<boost::mutex> lock(mx_);
直到另一个线程离开关键部分才返回。 为了使等待线程现在可以继续进行,互斥体需要解锁。 在boost中,一旦阻塞线程(第一个进入该部分的线程)离开具有关键部分的功能范围,该操作就会自动完成。 离开示波器将破坏变量mx_
,该变量允许创建和锁定另一个具有相同名称的互斥体。
编辑:您没有专门锁定一个变量,例如向量。 您锁定代码段,在该段中访问该变量。
class Receiver{
private:
boost::mutex mx_;
int *data_; // I need protection
public:
bool receive_data(){
// Prepare connection and do some stuff...
void some_function(){
// Before we access data_, we need to make sure only the current thread does so.
// Mutex will unlock once the scope of this function is left
boost::lock_guard<boost::mutex> lock(mx_);
// Access data_ here (mutex is locked)
//....
} // End of scope and mutex unlocks automatically since it's destroyed
return true; // Will unlock the mutex since the function's scope is left.
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.