pthreads_create 无缘无故地导致段错误

pthreads_create causing segment faults for no apparent reason

我一直在写一些需要在 C 中多线程的函数,pthreads 似乎是不行的 brainer.But 现在我已经写出来了它一直给我的段错误,有一堆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;
    }
}

代码有两个错误。

一个是运行main的线程可以终止,破坏opcount所在的堆栈。这可能发生在线程实际有机会终止之前。您不必等待它们终止。 (而且它们不会因为第二个错误而终止。)

第二个错误是您尝试取消的线程无法取消。他们不检查他们是否已被取消。他们不启用异步取消。

可能发生的情况是,当线程在第一个线程终止并成功后访问第一个线程堆栈上的对象时代码崩溃,如果幸运的话,进程在此之前终止,因为从 main 返回终止过程。