gpt4 book ai didi

c - 使用多线程对数字进行平方

转载 作者:行者123 更新时间:2023-11-30 17:04:34 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,通过创建 8 个线程来计算 1-10,000 的平方,每个线程将轮流计算一个数字的平方。这意味着一个线程将计算 1 的平方,另一个线程将计算 2 的平方,依此类推,直到所有线程计算一个数字的平方。然后一个线程将平方 9,等等,一直到 10,000。我的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>
#include <sys/types.h>

#define NUMBER_OF_THREADS 8
#define START_NUMBER 1
#define END_NUMBER 10000

FILE *f;

void *sqrtfunc(void *tid) { //function for computing squares
int i;
for (i = START_NUMBER; i<= END_NUMBER; i++){
if ((i % NUMBER_OF_THREADS) == pthread_self()){ //if i%8 == thread id
fprintf(f, "%lu squared = %lu\n", i, i*i); //then that thread should do this
}
}
}

int main(){
//Do not modify starting here
struct timeval start_time, end_time;
gettimeofday(&start_time, 0);
long unsigned i;
f = fopen("./squared_numbers.txt", "w");
//Do not modify ending here

pthread_t mythreads[NUMBER_OF_THREADS]; //thread variable
long mystatus;

for (i = 0; i < NUMBER_OF_THREADS; i++){ //loop to create 8 threads
mystatus = pthread_create(&mythreads[i], NULL, sqrtfunc, (void *)i);
if (mystatus != 0){ //check if pthread_create worked
printf("pthread_create failed\n");
exit(-1);
}
}
for (i = 0; i < NUMBER_OF_THREADS; i++){
if(pthread_join(mythreads[i], NULL)){
printf("Thread failed\n");
}
}
exit(1);

//Do not modify starting here
fclose(f);
gettimeofday(&end_time, 0);
float elapsed = (end_time.tv_sec-start_time.tv_sec) * 1000.0f + \
(end_time.tv_usec-start_time.tv_usec) / 1000.0f;
printf("took %0.2f milliseconds\n", elapsed);
//Do not modify ending here
}

我不知道我的错误在哪里。我在 main 中创建了 8 个线程,然后根据它们的线程 id (tid),我希望该线程对一个数字进行平方。截至目前,没有任何内容被打印到输出文件中,我不明白为什么。我的 tid 比较没有任何作用吗?任何提示表示赞赏。谢谢大家。

最佳答案

首先,您有意向每个线程传递一个参数,以便它知道它是哪个线程(从 0 到 7),这很好,但是您随后不再在线程内使用它(这会导致可能的情况之一)你的困惑)

其次,正如您在解释算法应该如何进行时所说的那样,您说每个线程必须对一组不同的数字进行平方,但所有线程都对同一组数字进行平方(实际上整组数字)

对此,您有两种方法:让每个线程对数字进行平方,然后再进行下一个八个位置(因此该算法是您的解释中描述的算法),或者您给出不同的集合(每个集合 1250 个连续数字)并让每个线程作用于自己单独的时间间隔。

也就是说,您必须重建 for 循环才能执行以下两项操作之一:

for (i = parameter; i < MAX; i += 8) ...

for (i = 1250*parameter; i < 1250*(parameter+1); i++) ...

这样,您就可以使用一组不同的输入数字来运行每个线程。

关于c - 使用多线程对数字进行平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35712458/

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