简体   繁体   中英

How to print result in order even if using threads in c?

I need to fine the first 10000 prime numbers using six threads and print them in order. How can i improve my solution?

#define N 6
#define S 10000

int a[S] = {0};

int is_prime(int n){
  int k;
  if(n == 2)
    return 1;
  for (int i = 2; i<n; i++){
    k = n%i;
    if(k == 0)
      return 0;
  }
  return 1;
}

void* prime_number(void* arg){
  int num = (int *) arg;
  for(int i = (S/N)*num; i<(S/N)*(num+1) && i<S; i++){
    if(is_prime(i))
      a[i] = i;
  }
  pthread_exit(NULL);
}

int main(int argc, char const *argv[]) {
  pthread_t *th;
  th = malloc(sizeof(pthread_t)*N);
  for(int i = 0; i<N; i++){
    pthread_create(&th[i], NULL, prime_number, i);
  }
  for(int i = 0; i<N; i++){
    pthread_join(th[i], NULL);
  }
  for(int i = 0; i<S; i++){
    if(a[i] != 0)
      printf("%d ", a[i]);
  }

  printf("\n");
  free(th);
  return 0;
}

In my solution I save everything in the a array and then I print it. Is there a better way to calculate if a number is prime and, if so, print it without save it in the array?

I need to print the numbers in order.

Get rid of your threads and just optimize your is_prime function. If you're trying to print out every single prime you've found, the printing is going to be a significant fraction of the work you're doing and that won't parallelize at all, so why bother with the threads?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM