有没有一种方法可以重用pthreads? [英] Is there a way to reuse pthreads?
问题描述
我有一个被称为数百万次的函数,并且此函数完成的工作是多线程的.功能如下:
I have a function that is called millions of times, and the work done by this function is multithreaded. Here is the function:
void functionCalledSoManyTimes()
{
for (int i = 0; i < NUM_OF_THREADS; i++)
{
pthread_create(&threads[i], &attr, thread_work_function, (void *)&thread_data[i]);
}
// wait
}
每次调用该函数时,我都会创建一个线程,并为每个线程提供其数据结构(在算法开始时已设置一次),以供在thread_work_function
中使用. thread_work_function
仅处理一系列数组,而thread_data
结构包含指向这些数组的指针以及每个线程负责的索引.
I'm creating the threads each time the function is called, and I give each thread its data struct (that's been set once at the beginning of the algorithm) to use in the thread_work_function
. The thread_work_function
simply processes a series of arrays, and the thread_data
struct contains pointers to those arrays and the indices that each thread is responsible for.
尽管以这种方式对算法进行多线程处理确实将性能提高了20%以上,但我的分析显示,对pthread_create的重复调用造成了相当大的开销.
Although multithreading the algorithm in this way did improve the performance by more than 20%, my profiling shows that the repetitive calls to pthread_create are causing a significant overhead.
我的问题是:是否有一种方法可以在每次调用函数时不调用pthread_create
来实现我的目标?
My question is: Is there a way to achieve my goal without calling pthread_create
each time the function is called?
问题已解决.
谢谢你们,我非常感谢您的帮助!我已经根据您的提示在此处写了一个解决方案.
Thank you guys, I really appreciate your help! I've written a solution here using your tips.
推荐答案
只需启动一组固定的线程并使用线程间通信系统(例如,环形缓冲区)将数据传递给进程即可.
Just start a fixed set of threads and use an inter-thread communication system (ring buffer, for instance) to pass the data to process.
这篇关于有没有一种方法可以重用pthreads?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!