【发布时间】:2015-04-19 14:20:32
【问题描述】:
你将如何在 c 中使用二进制归约和使用二进制信号量实现的屏障来做到这一点?这是我到目前为止的代码。它没有障碍,我对如何制作一个感到困惑。我需要互斥锁吗?
# include <stdio.h>
# include <pthread.h>
# define arrSize 10
struct StructMax
{
int iMax;
};
int arr[arrSize];
void *thread_search_max(void *);
int main()
{
pthread_t tid;
struct StructMax *st_main,*st_th;
int FinalMax;
st_main=(struct StructMax*)malloc(sizeof(struct StructMax));
int iCount;
for(iCount=0;iCount<arrSize;iCount++)
{
printf("Enter Value of arr[%d] :",iCount);
scanf("%d",&arr[iCount]);
}
pthread_create(&tid,NULL,thread_search_max,NULL);
st_main->iMax=arr[0];
for(iCount=1;iCount<arrSize/2;iCount++)
{
if(arr[iCount] > st_main->iMax)
{
st_main->iMax=arr[iCount];
}
}
pthread_join(tid,(void**)&st_th);
if(st_main->iMax >= st_th->iMax)
{
FinalMax=st_main->iMax;
}
else
{
FinalMax=st_th->iMax;
}
printf("Final Max : %d \n",FinalMax);
return 0;
}
void *thread_search_max(void *para)
{
struct StructMax *st;
st=(struct StructMax*)malloc(sizeof(struct StructMax));
int iCount;
st->iMax=arr[arrSize/2];
for(iCount=arrSize/2 + 1;iCount<arrSize;iCount++)
{
if(arr[iCount] > st->iMax)
{
st->iMax=arr[iCount];
}
}
pthread_exit((void*)st);
}
【问题讨论】:
-
Don't cast the return value of
malloc()in C。将您的分配写为:st_main = malloc(sizeof *st_main);。更短,没有毫无意义的强制转换,也更安全。 -
和几乎所有其他人一样,您投射
malloc()、which is not needed 但忽略它的返回值,这是不好的做法。另外,使用互斥体,不要使用全局变量,通过pthread_create的最后一个参数将数组传递给线程函数。请记住,每个malloc()都应该在某处与free()匹配。 -
信号量?障碍?我会避免他们在数组中搜索最大值,它们会损害性能足以将您推回直接的非并行执行。如果您这样做是为了提高性能,我会考虑使用 atomics (通过非常仔细的实现)甚至(如果您的架构允许您使用此 trick)使用 易变.
标签: c multithreading pthreads semaphore barrier