锁定多个生产者单一消费者 [英] Locking in Multiple producer single consumer

查看:243
本文介绍了锁定多个生产者单一消费者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解决多生产者单消费者问题与生成器生成整数和消费者使用所有这些整数(使用AVL树)排序列表。我应该如何锁定我的树数据结构?还是不必要?队列具有适当的锁定以用于推送和弹出操作。

  void consumer(NaiveQueue< nodeQ>& obj)
{
while(1)
{
nodeQ * temp;
temp = NULL;
temp = obj.pop();
if(temp)
{
cout<< \\\
Removed:< temp-> data;
root = insert(root,temp-> data); // **** lock this ????
delete temp
}
}
}

生产者(多线程生产者=主线程):

  void makeChildThread(int& newsockfd,char msg [MAXSZ],NaiveQueue< nodeQ> obj)
{
//从客户端接收
while(1)
{
int n = recv(newsockfd,msg,MAXSZ,0);
if(n == 0)
{
close(newsockfd);
break;
}
// msg [n] = 0;
// send(newsockfd,msg,n,0);
int val = atoi(msg);
if(val == 0)
{
break;
exit(0);
}

nodeQ * temp;
temp = new nodeQ();
temp-> data = val;
obj.push(temp);
cout<<\\\
Pushed:<< val;

cout<<\\\
Received:<< msg;
} // close while
cout<<\\\
Exit from thread;
}


解决方案

由所有生产者和消费者,访问需要同步。但是如果树由消费者使用,为什么要锁定它?锁定是不必要的,会导致额外的开销。


I am trying to solve a multiple producer single consumer problem with the producers generating integers and the consumer making a sorted list out of all these integers(using AVL tree). How should I be locking my tree data structure? Or is it unnecessary? The queue has proper locking for push and pop operations.

void consumer(NaiveQueue<nodeQ> &obj)
{
    while(1)
    {
    nodeQ *temp;
    temp=NULL;
    temp=obj.pop();
    if(temp)
      {
        cout << "\nRemoved : " << temp->data;
        root=insert(root,temp->data); //****lock this??????
        delete temp;
      }
   }  
}

Producer(Multithreaded producers => threads made in main):

void makeChildThread(int &newsockfd,char msg[MAXSZ],NaiveQueue<nodeQ> &obj)
{
   //receive from client
   while(1)
   {
    int n=recv(newsockfd,msg,MAXSZ,0);
    if(n==0)
    {
     close(newsockfd);
     break;
    }
    //msg[n]=0;
    //send(newsockfd,msg,n,0);
    int val=atoi(msg);
    if(val == 0)
    {
        break;
        exit(0);
    }

    nodeQ *temp;
    temp=new nodeQ();
    temp->data=val;
    obj.push(temp);
    cout<<"\nPushed : "<<val;

    cout<<"\nReceived :"<<msg;
   }//close while
    cout<<"\nExit from thread";
}

解决方案

Since the queue will be accessed by all producers and consumer, the access needs to synchronize. But if the tree is used by the single consumer, why lock it? Locking is unnecessary and will cause extra overhead.

这篇关于锁定多个生产者单一消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆