How can I synchronize three threads?

后端 未结 6 1921
北恋
北恋 2021-01-16 10:44

My app consist of the main-process and two threads, all running concurrently and making use of three fifo-queues:

The fifo-q\'s are Qmain, Q1 and Q2. Internally the

6条回答
  •  一个人的身影
    2021-01-16 11:12

    An example of how I would adapt the design and lock the queue access the posix way. Remark that I would wrap the mutex to use RAII or use boost-threading and that I would use stl::deque or stl::queue as queue, but staying as close as possible to your code:

    main-process:
    ...
    start thread Monitor
    ...
    while (!quit)
    {
        ...
        if (Qmain.count() > 0)
        {
            X = Qmain.get();
            process(X) 
                delete X;
        }
        ...
        //at some random time:
        QMain.put(Y);
        ...
    }
    
    Monitor:
    {
        while (1)
        {
            //obtain & package data
            QMain.put(data)
        }
    }
    
    fifo_q:
    template < class X* > class fifo_q
    {
        struct item
        {
            X* data;
            item *next;
            item() { data=NULL; next=NULL; }
        }
        item *head, *tail;
        int count;
        pthread_mutex_t m;
    public:
        fifo_q() { head=tail=NULL; count=0; }
        ~fifo_q() { clear(); /*deletes all items*/ }
        void put(X x) 
        { 
          pthread_mutex_lock(&m);
          item i=new item(); 
          (... adds to tail...); 
          count++; 
          pthread_mutex_unlock(&m);
        }
        X* get() 
        { 
          pthread_mutex_lock(&m);
          X *d = h.data; 
          (...deletes head ...); 
          count--; 
          pthread_mutex_unlock(&m);
          return d; 
        }
        clear() {...}
    };
    

    Remark too that the mutex still needs to be initialized as in the example here and that count() should also use the mutex

提交回复
热议问题