c - 在 C 中使用多线程显示质数

标签 c multithreading primes

在函数 printprime 中,我用四个线程中的每一个迭代每个元素,这几乎等同于一个单线程程序。我想将 i 增加 i=i+MAX_THREADS。我正在使用四个线程,因为我的笔记本电脑有四个处理器并且已经过全面优化。谁能告诉我如何调整 printprime 以便每个线程迭代一个数字。比如,线程 1 检查 2、6、10...线程 2 检查 3、7、11...等等。

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

#define N 30
#define MAX_THREADS 4

int prime_arr[N] = { 0 };

void *printprime(void *ptr) {
    int j, flag;
    int i = (int)(long long int)ptr;
    for (i = 2; i < N; i++) {
        flag = 0;
        for (j = 2; j <= i / 2; j++) {
            if (i % j == 0) {
                flag = 1;
                break;
            }
        }

        if (flag == 0) {
            prime_arr[i] = 1;
        }
    }
}

int main() {
    pthread_t tid[MAX_THREADS] = {{ 0 }};
    int count = 0;
    for (count = 0; count < MAX_THREADS; count++) {
        printf("\r\n CREATING THREADS %d", count);
        pthread_create(&tid[count], NULL, printprime, (void *)count);
    }
    printf("\n");
    for (count = 0; count < MAX_THREADS; count++) {
        pthread_join(tid[count], NULL);
    }

    int c = 0;
    for (count = 0; count < N; count++)
        if (prime_arr[count] == 1)
            printf("%d ", count);

    return 0;
}

最佳答案

为了达到理想效果,将函数 void *printprime(void *ptr) 中的变量 i 增加 MAX_THREADS(在您的例子中为 4)。

注意printf("Thread id[%d] checking [%d]\n",pthread_self(),i); 用于显示哪个线程正在检查哪个值。

以下代码可能会有帮助:

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

#define N 30
#define MAX_THREADS 4

int prime_arr[N]={0};

void *printprime(void *ptr)
{
    int  j,flag;
    int i=(int)(long long int)ptr;
    while(i<N)
    {
        printf("Thread id[%d] checking [%d]\n",pthread_self(),i);
        flag=0;
        for(j=2;j<=i/2;j++)
        {
            if(i%j==0)
            {
                flag=1;
                break;
            }
        }

        if(flag==0 && (i>1))
        {
            prime_arr[i]=1;
        }
        i+=MAX_THREADS;
  }
}

int main()
{
    pthread_t tid[MAX_THREADS]={{0}};
    int count=0;
    for(count=0;count<MAX_THREADS;count++)
    {
        printf("\r\n CREATING THREADS %d",count);
        pthread_create(&tid[count],NULL,printprime,(void*)count);
    }
    printf("\n");
    for(count=0;count<MAX_THREADS;count++)
    {
        pthread_join(tid[count],NULL);
    }

    int c=0;
    for(count=0;count<N;count++)
        if(prime_arr[count]==1)
            printf("%d ",count);

    return 0;
 }

关于c - 在 C 中使用多线程显示质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44881796/

相关文章:

c - c语言打印动态数组

c - strtok() 的用法

java - 使用 JFrame 使用 Java 编写简单时钟

c++ - 使套接字服务器接受多个客户端

c# - .NET 中是否有公开可用的素数表

C:共享内存和 fork ,打印语句执行多次

c - 退出时不最小化窗口吗?

javascript - 来自 C++ 线程的节点 FFI 回调

performance - Haskell 中的素筛

performance - 整数 n 的除数列表 (Haskell)