判断质数,使用多线程和信号量

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

#define LEFT    30000000
#define RIGHT   30000200
#define THRNUM  4

static int current_num = 0;
static int finished = 0;

static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *thr_primer(void *p);

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

int main() {
    pthread_t tid[THRNUM];
    int i, err;

    // 创建线程
    for (i = 0; i < THRNUM; i++) {
        err = pthread_create(&tid[i], NULL, thr_primer, NULL);
        if (err) {
            fprintf(stderr, "pthread_create(): %s\n", strerror(err));
            exit(1);
        }
    }

    // 主线程生产数据
    for (i = LEFT; i <= RIGHT; i++) {
        pthread_mutex_lock(&mut);
        while (current_num != 0) {
            pthread_cond_wait(&cond, &mut);
        }
        current_num = i;
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mut);
    }

    // 通知子线程结束
    pthread_mutex_lock(&mut);
    while (current_num != 0) {
        pthread_cond_wait(&cond, &mut);
    }
    finished = 1;
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mut);

    // 等待子线程
    for (i = 0; i < THRNUM; i++) {
        pthread_join(tid[i], NULL);
    }

    pthread_mutex_destroy(&mut);
    pthread_cond_destroy(&cond);

    exit(0);
}

void *thr_primer(void *p) {
    while (1) {
        pthread_mutex_lock(&mut);
        while (current_num == 0 && !finished) {
            pthread_cond_wait(&cond, &mut);
        }
        if (finished) {
            pthread_mutex_unlock(&mut);
            break;
        }
        int n = current_num;
        current_num = 0;
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mut);

        if (is_prime(n)) {
            printf("Thread %ld: %d is prime\n", pthread_self(), n);
        }
    }
    pthread_exit(NULL);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值