如何在C语言中实现多线程因子分解

avatar
作者
猴君
阅读量:0

在C语言中,可以使用POSIX线程库(pthread)来实现多线程因子分解

#include<stdio.h> #include <stdlib.h> #include <pthread.h> #include <math.h>  typedef struct {     int number;     int start;     int end; } FactorData;  void *find_factors(void *arg) {     FactorData *data = (FactorData *)arg;     int number = data->number;     int start = data->start;     int end = data->end;      for (int i = start; i <= end; i++) {         if (number % i == 0) {             printf("Thread %lu: %d is a factor of %d\n", pthread_self(), i, number);         }     }      return NULL; }  int main() {     int number;     printf("Enter the number to be factorized: ");     scanf("%d", &number);      int num_threads = 4;     pthread_t threads[num_threads];     FactorData data[num_threads];      int range = (int)sqrt(number) / num_threads;      for (int i = 0; i < num_threads; i++) {         data[i].number = number;         data[i].start = i * range + 1;         data[i].end = (i + 1) * range;         pthread_create(&threads[i], NULL, find_factors, (void *)&data[i]);     }      for (int i = 0; i < num_threads; i++) {         pthread_join(threads[i], NULL);     }      return 0; } 

这个程序首先接收一个整数输入,然后创建4个线程。每个线程负责查找一部分范围内的因子。线程之间不会重复查找因子。最后,主线程等待所有子线程完成任务。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!