簡體   English   中英

Pthread傳遞函數到池

[英]Pthread Passing Function to Pool

我正在從頭開始創建一個線程池作為賦值的一部分,並且能夠創建線程池,然后為每個創建的線程傳遞一個不斷循環的函數。 我的問題是如何接受輸入並將其傳遞給已經執行的pthread。 在搞清楚之后,我將添加互斥鎖以將函數鎖定到特定線程,但我無法進入該部分。

class ThreadPool{
public:
    ThreadPool(size_t threadCount);
    int dispatch_thread(void *(dispatch_function(void *)), void *arg);
    bool thread_avail();
    int numThreads;
    pthread_t * thread;
    pthread_mutex_t * mutexes;
};


int ThreadPool::dispatch_thread(void *(dispatch_function(void *)), void *arg){

  flag = 1;
//This is where I would like to pass the function the running pthread
}

void *BusyWork(void *t)
{
  while(true){
  //This is where I would like to run the passed function from each thread
  //I can run the passed function by itself, but need to pass it to the threadpool
  }
}

ThreadPool::ThreadPool(size_t threadCount){
 pthread_t thread[threadCount];

 for(t=0; t<threadCount; t++) {
 //printf("Main: creating thread %ld\n", t);
 rc = pthread_create(&thread[t], NULL, BusyWork, (void *)t); 
 }
}

void *test_fn(void *par)
{
   cout << "in test_fn " << *(int *)par << endl;
}

int main (){
  ThreadPool th(3);
  int max = 100;

  for (int i = 0; i < 20; i++) {
    max = 100 * i;
    th.dispatch_thread(test_fn, (void *)&max);
    sleep(1);
  }
}

我能想到的最好的模式是使用某種隊列將消息傳遞給線程池。 這些消息可能包含要運行的函數以及用於關閉線程池的一些控制消息。 正如您已經猜到的那樣,隊列必須是線程安全的。

隊列的一個簡單方法是使用固定大小的數組,然后將其轉換為循環緩沖區。 該數組將具有一個Mutex以在訪問數組時鎖定它,並使用Condition Variable來喚醒線程池線程。

將項目放入隊列時,我們鎖定互斥鎖,添加到隊列,然后使用條件變量向線程池發送信號。

線程池中的每個正在運行的線程將通過鎖定互斥鎖並等待條件變量(自動解鎖互斥鎖)來啟動生命。 喚醒時,它將從隊列中刪除該項,然后解鎖互斥鎖。 它現在是免費的。 完成后,它會進入睡眠狀態,直到重新發出信號為止。

作為一般建議,避免在線程之間共享內存,因為這會導致競爭條件(如果訪問不受保護)或導致互鎖(如果訪問被鎖定)。 還要避免在執行任何長時間運行操作時鎖定互斥鎖,例如調用new(malloc),刪除(free)或任何系統調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM