gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:26:28 27 4
gpt4 key购买 nike

对于我的作业,我需要计算区间 (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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com