我正在从头开始创建一个线程池作为赋值的一部分,并且能够创建线程池,然后将每个创建的线程传递一个不断循环的函数。我的问题是我如何接受输入并将它传递给正在执行的pthread。在弄清楚这一点之后,我将添加互斥锁来将函数锁定到特定的线程,但我无法进入该部分。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);
}
}
共享数据+(互斥量,条件变量)应该这样做 – sehe
我同意,我只是不知道传递dispatch_thread函数的void *(dispatch_function(void *)),void * arg)参数的正确方法作为条件变量或全局声明的方式。我不知道是否有某种基于语法的方法来执行此操作,或者是否有可用的全新选项。 – patemotter