【发布时间】:2011-12-11 08:20:14
【问题描述】:
我正在从头开始创建一个线程池作为分配的一部分,并且能够创建线程池,然后将每个创建的线程传递给一个不断循环的函数。我的问题是如何接受输入并将其传递给已经执行的 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);
}
}
【问题讨论】:
-
共享数据+(互斥体,条件变量)应该这样做
-
我同意,我只是不知道将 dispatch_thread 函数的 void *(dispatch_function(void *)), void *arg) 参数作为条件变量或传递让它在全球范围内声明。我不知道是否有某种基于语法的方法可以做到这一点,或者是否有一个全新的选项可用。
标签: c++ pthreads posix threadpool