【发布时间】:2021-08-25 16:43:33
【问题描述】:
我一直在编写一些需要在 C 中进行多线程处理的函数,pthreads 似乎很简单。但是现在我已经写出来了,它一直在给我的段错误,并带有一堆 printf() 语句并注释掉部分代码我发现 pthread_create 导致了这些,任何帮助将不胜感激!据我所见,我将参数传递给 pthread_create 似乎非常好。
代码:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdbool.h>
typedef unsigned long long ll;
struct opscount{
ll faddpthread;
ll fsubpthread;
ll fmulpthrea;
ll fdivpthread;
};
int main(){
int total_thread,time;
printf("Enter total number of threads : ");
scanf("%i",&total_thread);
printf("Time to run the test : ");
scanf("%i",&time);
struct opscount opcount[total_thread];
pthread_t thread[total_thread];
//---------------------start of fadd test----------------------------------
for(int i=0;i<total_thread;i++)
{
opcount[i].faddpthread=0;
pthread_create(&thread[i],NULL,faddtf,opcount+i);
}
int optime=time/4;
sleep(optime);
for(int i=0;i<total_thread;i++)
{
pthread_cancel(thread[i]);// kills the threads
}
}
线程函数是:
void *faddtf(void *oppthread)
{
double c=0.75665;
while(true)
{
c+=v1+v2+v3+v4+v5;
((struct opscount *)oppthread)->faddpthread+=5;
}
}
【问题讨论】:
-
好吧,经过一番谷歌搜索后,我发现了这个:linuxquestions.org/questions/linux-newbie-8/… 我认为将 stuct 作为参数传递给 pthread_create 会导致问题,我将其换成了数组,它肯定修复了错误。
-
Re, "...struct as parameter...array..." 这没有意义。唯一可以传递给新线程的是一个指针。只要(a)它指向的东西在线程的生命周期内继续存在,指针指向的东西就无关紧要了。线程,以及 (b)
pthread_create(..., my_pointer)的调用者和线程中运行的代码都同意该事物的大小和类型。
标签: c multithreading pthreads