作为我使用pthread的第一次真正尝试,我希望将我已经编写的一个应用程序改写为使用线程。
我心目中的范例基本上是有一个“主”线程,它迭代要处理的数据项的列表,为每个数据项启动一个新线程,MAX_THREADS线程在任何给定的时间运行(直到剩余任务的数量小于这个值),每个线程在列表中的单个数据元素上执行相同的任务。
当任何线程完成其任务并返回(或pthread_exit()'ed)时,主线程需要知道,它会立即启动一个新线程来执行列表中的下一个任务。
我想知道的是,人们使用这种设计的首选方法是什么?抛开数据方面的考虑,使用哪组最简单的pthread函数来实现这一点呢?显然,pthread_join()是一种对线程进行“检查”的方法。
早期的实验一直使用结构,作为最后一个参数传递给pthread_create(),该结构包含一个名为"running“的元素,线程在启动时将该元素设置为true,并在返回前将其重置。主线程只需为循环中的每个线程检查此结构元素的当前值。
下面是程序用于线程管理的数据:
typedef struct thread_args_struct
{
char *data; /* the data item the thread will be working on */
int index; /* thread's index in the array of threads */
int thread_id; /* thread's actual integer id */
int running; /* boolean status */
int retval; /* value to pass back from thread on return */
} thread_args_t;
/*
* array of threads (only used for thread creation here, not referenced
* otherwise)
*/
pthread_t thread[MAX_THREADS];
/*
* array of argument structs
*
* a pointer to the thread's argument struct will be passed to it on creation,
* and the thread will place its return value in the appropriate struct element
* before returning/exiting
*/
thread_args_t thread_args[MAX_THREADS];
这看起来像是一个合理的设计吗?有没有一种更好、更标准化的方法来监控线程的运行/退出状态,一种更"pthreads-y“的方法?我希望使用最简单、最清晰、最干净的机制,不会导致任何意想不到的复杂情况。
感谢您的反馈。
发布于 2012-04-14 08:48:55
与其说是“pthreads y”方式,不如说是(通用的)多线程方式。你所拥有的东西没有什么问题,但它比它需要的更复杂和低效。
更标准的设计是使用线程池。主线程产生一堆读队列的工作线程。主设备将工作放入队列中,所有的工作人员都尝试处理队列中的工作。这消除了不断启动和终止线程的需要(尽管更复杂的池可以有一些机制来根据工作负载增加/减少池大小)。如果线程必须返回数据或状态信息,它们可以使用主线程可以读取的输出队列(可能只是指向实际数据的指针)。
这仍然留下了一个问题,当你完成处理时,如何摆脱线程。同样,这是一种主机-工人关系,因此建议主机告诉从机关闭自己。这相当于使用某个程序开关(如您当前拥有的),在某处使用条件变量,发送信号,或取消线程。这里有很多关于这个主题的问题(和很好的答案)。
https://stackoverflow.com/questions/10149569
复制相似问题