使用多个线程计算给定间隔的总和

标签 c multithreading

对于我的作业,我需要计算区间 (0,N) 内的整数平方(例如 (0,50)),以便负载在线程之间平均分配(例如 5 个线程)。我一直在建议使用间隔中的小块并将其分配给线程。为此,我使用队列。这是我的代码:

#include <stdio.h>
#include <pthread.h>

#define QUEUE_SIZE 50
typedef struct {
    int q[QUEUE_SIZE];
    int first,last;
    int count;
} queue;

void init_queue(queue *q)
{
    q->first = 0;
    q->last = QUEUE_SIZE - 1;
    q->count = 0;
}

void enqueue(queue *q,int x)
{
    q->last = (q->last + 1) % QUEUE_SIZE;
    q->q[ q->last ] = x;
    q->count = q->count + 1;
}

int dequeue(queue *q)
{
    int x = q->q[ q->first ];
    q->first = (q->first + 1) % QUEUE_SIZE;
    q->count = q->count - 1;
    return x;
}

queue q; //declare the queue data structure

void* threadFunc(void* data)
{   
    int my_data = (int)data; /* data received by thread */

    int sum=0, tmp;

    while (q.count)
    {
        tmp = dequeue(&q);
        sum = sum + tmp*tmp;
        usleep(1);
    }
    printf("SUM = %d\n", sum);

    printf("Hello from new thread %u - I was created in iteration %d\n",pthread_self(), my_data);   
    pthread_exit(NULL); /* terminate the thread */
}

int main(int argc, char* argv[])
{
    init_queue(&q);
    int i;

    for (i=0; i<50; i++)
    {
        enqueue(&q, i);
    }

    pthread_t *tid = malloc(5 * sizeof(pthread_t) );

    int rc; //return value

    for(i=0; i<5; i++)
    {
        rc = pthread_create(&tid[i], NULL, threadFunc, (void*)i);
        if(rc) /* could not create thread */
        {
            printf("\n ERROR: return code from pthread_create is %u \n", rc);
            return(-1);
        }
    }

    for(i=0; i<5; i++)
    {
        pthread_join(tid[i], NULL);
    }

}

输出并不总是正确的。大多数时候它是正确的,40425,但有时,该值更大。是否因为线程并行运行并同时访问队列(我笔记本电脑上的处理器是intel i7)?如果您能就我的担忧提供反馈,我将不胜感激。

最佳答案

我认为与这里其他人的建议相反,您根本不需要任何同步原语,例如信号量或互斥体。像这样的事情:

给定一些数组,例如

int values[50];

我会创建几个线程(例如:5),每个线程都会获取一个指向结构的指针,该结构具有 values 数组中的偏移量和要计算的多个平方,例如

typedef struct ThreadArgs {
    int *values;
    size_t numSquares;
} ThreadArgs;

然后您可以启动线程,每个线程被告知处理 10 个数字:

for ( i = 0; i < 5; ++i ) {
    ThreadArgs *args = malloc( sizeof( ThreadArgs ) );
    args->values = values + 10 * i;
    args->numSquares = 10;
    pthread_create( ...., threadFunc, args );
}

然后每个线程简单地计算分配给它的平方,例如:

void *threadFunc( void *data )
{
    ThreadArgs *args = data;
    int i;
    for ( i = 0; i < args->numSquares; ++i ) {
        args->values[i] = args->values[i] * args->values[i];
    }
    free( args );
}

最后,您只需使用 pthread_join等待所有线程完成,之后您的方 block 就会出现在 values 数组中。

关于使用多个线程计算给定间隔的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23622331/

相关文章:

c - 如何在 Linux 源代码中包含用户级 C 程序以与 Linux 内核一起编译?

c++ - strlen() 给出错误的大小,导致数组中出现空字节

java - Java中的多线程文件读取

ios - 如何创建和管理串行后台线程

java - Akka java 线程在多个 JVM 上阻塞

java - 服务无法正常工作

c - 从地址获取套接字描述符?

c - (1.0e300 + pow(2.0, -30.0) > 1.0) 在 STDC 中究竟做了什么?

c - 在 Visual Studio 2010 中链接不同的 C 源文件

java线程和jtabbedpane