2010-10-05 60 views
1

我在寫一個小小的試用項目,我需要將值類型爲QueuList的對象按值傳遞給線程池線程。它是一個Boost線程池,我使用綁定將參數傳遞給線程。按值向另一個線程傳遞對象

出於某種原因,我似乎無法到我的項目傳遞給由值線程池線程...

任何人可以幫助我在做什麼錯?

void ConsumerScheduler() 
{ 
    int count = 0; 
    typedef boost::intrusive::list<QueuList> List; 
    while (true) 
    { 
     WaitForSingleObject(hConsumer, 2000); // Wait for hConsomuer to become > 0 
     { 
      //lock Queue 
      QueuList *item = NULL; 
      boost::mutex::scoped_lock lock(mtx); 
      {//Scope of lock 
       if (lst->size() == 0) 
       { 
        printf("List is emtpy"); 
        continue; 
       } 
       else 
       { 
        List::iterator iter(lst->begin()); 
        item = &*iter; 
        lst->pop_front(); //Item is removed from list, so pointer is no longer available!!! 
        printf("Popped item off list. List current size: %d\n",lst->size()); 
        count++; 
       } 
      } 
      //Pass to threadpool 
      tpp.schedule(boost::bind(taskfunc,*item)); //it will not accept *item or item in this bind function to pass it by value 
      total--; 
      if (total == 0) 
      { 
       printf("Total is now zero!\nCount is %d\n", count); 
      } 
      if (count == 5) 
       break; 

      ReleaseSemaphore(hProducer,total , NULL); // Release the hProducer semaphore, possibly waking producer 
     } 
    } 
} 

//Thread pool thread function 
void taskfunc(QueuList list) 
{ 
    boost::mutex::scoped_lock lock(mtx); 
    { 
     std::string name= list.GetName(); 
     printf("Name gotten: %s",name); 
    } 

} 

我想按值傳遞的原因是使每一個線程池線程都有它自己的指針被從列表中的第一個函數刪除的對象的副本,這將導致一個錯誤,如果我通過引用傳遞。

+1

請出示tpp'是如何定義'和編譯器的輸出 – 2010-10-05 14:03:58

回答

2

您可以通過在隊列和線程池計劃中使用boost::shared_ptr<QueueList>來解決此問題。在一些STL中沒有unique_ptr時,最好表達了您希望的共享數據。

+0

其實這並不:'shared_ptr'大約是共同擁有,該只有表示單實例切換的標準智能指針是'unique_ptr',並且在所有的STL中都不可用。 'shared_ptr'是同時代最差的替代品。 – 2010-10-05 14:28:35

+0

@Matthieu - 我認爲最好提供一個廣泛支持以避免混淆的解決方案 – 2010-10-05 14:32:04

+0

我同意這個解決方案很好,但我會修改「表示單一實例手動」的評論。分享和單身並不真正混合,語義明智。 – 2010-10-05 15:48:55

1

錯誤發生在運行時或編譯時間?

我創建了自己的代碼,沒有編譯錯誤。

我不使用boost,但是,如果您在運行時遇到錯誤,我認爲錯誤在範圍鎖定中。範圍鎖不應該在括號內?

編輯:我沒有權限發表評論,所以我張貼的答案

+0

編譯時錯誤,而不是範圍鎖。 – 2010-10-05 14:26:13

+0

什麼錯誤?你已經實現了QueuList的複製構造函數? – 2010-10-05 14:31:32

+0

我明白'boost :: mutex :: scoped_lock lock(mtx);'應該放在*範圍內,而不是在@Bruno Caponi所說的範圍內。 – j4x 2011-03-24 12:24:31

相關問題