线程池筛质数
作者:互联网
多线程通过竞争获取数据计算是否为质数。
例程:pthread_pool_busy.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#define LEFT 30000000
#define RIGHT 30000200
#define THRNUM 4
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; //初始化互斥量
static int num=0;
static void *p_func(void *p);
/*
* > 0 //可用数据
* = 0 //等待数据
* = -1 //数据计算完毕
*/
int main()
{
int i,err;
pthread_t tid[THRNUM]; //线程数组
for(i=0;i<4;i++)
{
err = pthread_create(tid+i,NULL,p_func,(void *)i); //创建线程
if(err)
{
fprintf(stderr,"pthread_create():%s\n",strerror(err));
exit(1);
}
}
for(i=LEFT;i<=RIGHT;i++) //循环输出数据
{
pthread_mutex_lock(&mut); //操作数据前上锁
while(num !=0)
{
pthread_mutex_unlock(&mut); //数据未被取走时解锁
sched_yield(); //出让调度器
pthread_mutex_lock(&mut); //加锁
}
num = i;
pthread_mutex_unlock(&mut); //操作完解锁
}
pthread_mutex_lock(&mut); //加锁
while(num !=0)
{
pthread_mutex_unlock(&mut); //数据未被取走解锁
sched_yield(); //出让调度器
pthread_mutex_lock(&mut); //解锁
}
num =-1;
pthread_mutex_unlock(&mut); //解锁
for(i=0;i<4;i++)
{
pthread_join(tid[i],NULL); //等待线程结束
}
pthread_mutex_destroy(&mut); //销毁互斥锁
exit(0);
}
static void *p_func(void *p)
{
int j,mark;
int i;
while(1)
{
pthread_mutex_lock(&mut); //加锁
while(num==0)
{
pthread_mutex_unlock(&mut); //未给数据时解锁
sched_yield(); //出让调度器
pthread_mutex_lock(&mut); //加锁
}
if(num ==-1)
{
pthread_mutex_unlock(&mut); //任务完成解锁退出
break;
}
i = num;
num =0;
pthread_mutex_unlock(&mut); //解锁
mark =0;
for(j=2;j<i/2;j++)
{
if(i%j ==0)
{
mark =1;
break;
}
}
if(mark ==0)
printf("[%d]%d is primer\n",(int)p,i);
}
pthread_exit(NULL); //退出线程
}
编译文件:Makefile
CFLAGS +=-pthread
LDFLAGS +=-pthread
标签:mut,mutex,质数,unlock,num,线程,pthread,池筛,解锁 来源: https://www.cnblogs.com/linux-learn/p/16516156.html