现在的位置: 首页 > 综合 > 正文

thread execute primer

2017年12月15日 ⁄ 综合 ⁄ 共 756字 ⁄ 字号 评论关闭

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

#define LEFT 30000000
#define RIGHT 30000200
#define THRNUM (RIGHT-LEFT+1)

static void *thr_prime(void *p);

//
struct thr_arg_st
{
 int n;
};

int main()
{
 pthread_t tid[THRNUM];
 int i,err;
 pid_t pid;
 struct thr_arg_st *p;
 void *ptr;

 for(i = LEFT; i <= RIGHT; i++)
 {
  p = malloc(sizeof(*p));//
  p->n = i;//
  err = pthread_create(tid+(i-LEFT),NULL,thr_prime,p);
  if(err) 
  {
   fprintf(stderr,"pthread_create():%s\n",strerror(err));
   exit(1);
  }

 }

 for(i = LEFT; i <= RIGHT; i++)
 {
  pthread_join(tid[i-LEFT],&ptr);
  free(ptr);
 }

 exit(0);
}

static void *thr_prime(void *p)
{
 int i,j,mark;

 i = ((struct thr_arg_st *)p)->n;
// free(p);

 mark = 1;
 for(j = 2; j < i/2 ; j++)
 {
  if(i % j == 0)
  {
   mark = 0;
   break; 
  }
 }
 if(mark)
  printf("%d is a prime.\n",i);

 pthread_exit(p);
}

 

 

 

 

抱歉!评论已关闭.