最多允许四个线程
main.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "primer.h"
#include <string.h>
#include <unistd.h>
#define LEFT 30000000
#define RIGHT 30000200
#define THRNUM (RIGHT-LEFT +1)
#define N 4 //允许同时存在4个线程
static struct the_thread *mthread;
static void *func(void *p){
int *num = p;
int j;
int flag=0;
for(j=2;j<*num /2;j++){
if(*num % j == 0){
flag = 1;
break;
}
}
if(!flag){
printf("[%d] is a primer\n",*num);
}
free(num);
thread_add(mthread,1);
pthread_exit(NULL);
}
int main(){
int i;
int err;
pthread_t itd[THRNUM];
mthread = thread_num_init(N);//初始化,同一时刻允许有4个线程同时工作
if(mthread == NULL){
exit(1);
}
int *num;
for(i=LEFT;i<=RIGHT;i++){
num = malloc(sizeof(int));
*num = i;
thread_sub(mthread,1);//查看是否能够申请1个线程,如果不能阻塞等待
err = pthread_create(itd+i-LEFT,NULL,func,num);//创建线程
if(err){
exit(1);
}
}
for(i = LEFT; i <= RIGHT; i++){//收尸
pthread_join(itd[i-LEFT],NULL);
}
thread_num_destroy(mthread);
exit(0);
}
primer.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "primer.h"
typedef struct the_thre{
int value;
pthread_mutex_t mutex;
pthread_cond_t cond;
}p_thread;
the_thread *thread_num_init(int number){
p_thread *methread;
methread = malloc(sizeof(*methread));
if(methread == NULL){
return NULL;
}
methread->value = number;
pthread_mutex_init(&methread->mutex,NULL);
pthread_cond_init(&methread->cond,NULL);
return methread;
}
int thread_add(the_thread *mythread,int number){
p_thread *methread = mythread;
/*if NULL*/
pthread_mutex_lock(&methread->mutex);
methread->value += number;
pthread_cond_broadcast(&methread->cond);
pthread_mutex_unlock(&methread->mutex);
return number;
}
int thread_sub(the_thread *mythread,int number){
p_thread *methread = mythread;
/*if null*/
pthread_mutex_lock(&methread->mutex);
while(methread->value < number){
pthread_cond_wait(&methread->cond,&methread->mutex);
}
methread->value -= number;
pthread_mutex_unlock(&methread->mutex);
return number;
}
int thread_num_destroy(the_thread *mythread){
p_thread *methread=mythread;
pthread_mutex_destroy(&methread->mutex);
pthread_cond_destroy(&methread->cond);
free(methread);
return 0;
}
primer.h
#ifndef PRIMER_H__
#define PRIMER_H__
typedef void the_thread;
the_thread* thread_num_init(int);//初始化,线程数量
int thread_add(the_thread*,int);//在当前线程pread_wait()后,给线程数量加1
int thread_sub(the_thread*,int);//在创建完一个线程后,还能够创建的线程数量减一,如果当前已没有线程
//即四个线程都存在,会阻塞等待 直到可以申请新的线程,如果你
int thread_num_destroy(the_thread *);//free 并destroy mutex 和cond
#endif
程序在linux下跑的,注释我现在不想写,我认为如果你了解pthread_create pthread_mutex_lock,pthread_cond_wait等的,应该比较容易看懂。如果你有什么问题或者需要欢迎联系我755465928@qq.com,另外欢迎与我交流。