如何在C中具有动态线程数

用户名

我想使用线程在c中计算数学求和。(∑x ^ i,从0到N)每个线程应计算求和项的每个项,最后在程序中,程序应将所有所有项求和并打印出来。我应该如何动态地设置线程数?这是我的代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>

pthread_t sadaf[10];
int i,a[10];
long int x,N;
int sum=0;
pthread_mutex_t mtx;

void *Myfun(void *tid)
{
    int *ThreadID=(int *)tid;
    pthread_mutex_lock(&mtx);
    printf("The thread with id of %d calculated x^i\n",*ThreadID);
    a[*ThreadID]=pow(x,*ThreadID);
    sum=sum+a[*ThreadID];
    pthread_mutex_unlock(&mtx);

}

int main()
{
     int d[10] = {0};
     printf("->**************************************************************************<-\n");
     printf("This program will calculate the following function:\n-> ∑x^i ,From 0 to N \n");
     printf("->**************************************************************************<-\n");
     printf("Please enter x:\n");
     scanf("%ld",&x);
     printf("Please enter N:\n");
     scanf("%ld",&N);

    for (i=0; i<N; i++)
    {
        d[i] = i;
        pthread_create(&sadaf[i],NULL,Myfun,(void *)&d[i]);
    }
    for (i=0; i<N; i++)
    {
        pthread_join(sadaf[i],NULL);
    }


    printf("The sum is: %d\n",sum);

}
贾伯沃基(Jabberwocky)

d数组可以容纳10个值,因此,如果N大于10,则存在超出范围的问题:

    int d[10] = {0};
    ...

    for (i=0; i<N; i++)
    {
        d[i] = i;      // if i > 10 => you access out of bounds => problem

您对其他阵列也有同样的问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在C ++中设置线程数

如何在 C++ 中运行具有仅调用线程的函数的类的多个对象?

如何在NativeScript中创建具有动态行数和列数的表?

如何在RavenDB中存储具有动态属性的C#对象?

如何在C ++中循环遍历具有不同长度的动态2D数组

如何在具有动态对齐要求的C ++中创建对象?

如何在php中动态创建具有计数的对象?

如何在React中映射具有动态键的对象?

如何在Makefile中具有动态目标?

扑。-如何在Gridview中具有动态crossAxisCount

如何在CustomMultiChildLayout中具有动态高度?

如何在 TEntity 中动态搜索具有值的属性?

在Java中运行具有返回值的动态线程数

如何在Java中创建动态线程

如何在工作表中动态创建具有列数的数组,以删除多列中的重复项

如何在C程序中获取进程和线程数?

如何在 C# 中拥有动态属性

如何在Spring应用程序中具有每个线程但可重用的对象(PubNub)?

如何在finally块中停止具有无限循环的线程

如何在ASP .NET Core请求管道中仍具有未完成的子线程的同时停止线程重用?

如何在具有动态列数的XML上使用XSLT作为HTML表获取结果

具有指针的C ++中的动态Arary

当 ControlFlow 中的 FlatFile 具有动态名称时,如何在 SSIS 中删除它?

如何在LESS CSS中具有动态类名并将其用作函数中的值

如何在车把中具有动态索引的对象中访问数组?

如何在VBA中的excel中创建具有文件属性的动态对象列表

如何在Java中动态调整缓存线程池的大小

如何在C中实现具有多个节点的链表?

如何在C绑定中具有数组类型?