Locking in Multiple producer single consumer

ε祈祈猫儿з 提交于 2019-12-12 02:46:23

问题


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";
}

回答1:


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.



来源:https://stackoverflow.com/questions/23589828/locking-in-multiple-producer-single-consumer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!