如何与QUOT;多线程" C $ C $Ç [英] How to "multithread" C code
问题描述
我用C编写的一个数字运算应用程序是怎样的一个主回路,对于每个值呼吁,增加我,一个执行一些计算函数的值。我读到的多线程,和我正在考虑学习一些关于它在C.我不知道如果以某种方式一般code像我可能是自动的多线程以及如何。
感谢
Pd积。为了让我的code的想法,让我们说,它是这样的:
主(...)
对于(I = 0; I&下; = ntimes; i ++在)get_result(X [I]中,值Y [i],结果由[i]);
...
无效get_result(浮法X,浮法Y,float结果){
结果= SQRT(日志(X)+日志(γ)+ COS(EXP(X + Y));
(和一些更类似的数学运算)
}
一种可以替代的多线程您code将使用的pthreads (提供了更多的precise比OpenMP的控制)。
假设 X
,是
&安培; 结果
是全局变量数组,
的#include< pthreads.h中>...无效* get_result(无效*参数)//参数是一个虚拟的指针
{
...
}诠释的main()
{
...
*的pthread_t TID =的malloc(ntimes *的sizeof(的pthread_t));对于(i = 0; I< ntimes;我++)
在pthread_create(安培; TID [Ⅰ],NULL,get_result,NULL);... //做一些工作无关的结果对于(i = 0; I< ntimes;我++)
在pthread_join(TID [I],NULL);
...
}
(编译你code。与 GCC prog.c中-lpthread
)
I have a number crunching application written in C. It is kind of a main loop that for each value calls, for increasing values of "i", a function that performs some calculations. I read about multithreading, and I am considering learning a bit about it, in C. I wonder if somehow general code like mine could be automatically multithreaded and how.
Thanks
P.D. To get an idea about my code, let's say that it is something like this:
main(...)
for(i=0;i<=ntimes;i++)get_result(x[i],y[i],result[i]);
...
void get_result(float x,float y,float result){
result=sqrt(log (x) + log (y) + cos (exp (x + y));
(and some more similar mathematical operations)
}
One alternative to multithread your code would be using pthreads ( provides more precise control than OpenMP ).
Assuming x
, y
& result
are global variable arrays,
#include <pthread.h>
...
void *get_result(void *param) // param is a dummy pointer
{
...
}
int main()
{
...
pthread_t *tid = malloc( ntimes * sizeof(pthread_t) );
for( i=0; i<ntimes; i++ )
pthread_create( &tid[i], NULL, get_result, NULL );
... // do some tasks unrelated to result
for( i=0; i<ntimes; i++ )
pthread_join( tid[i], NULL );
...
}
(Compile your code with gcc prog.c -lpthread
)
这篇关于如何与QUOT;多线程&QUOT; C $ C $Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!