c - Linux C 中的多线程

标签 c multithreading ubuntu pthreads

我正在尝试计算 PI 的值。我有多个线程正在计算 PI。如果我的 PI 和原始 PI 之间的差异小于 0.0001,我想向其他线程发送信号并完成线程。另一个线程(接收信号)打印出我的 PI 值。

我编写了程序,但有时它可以正常工作,有时则不能:)有人可以帮助我吗?

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

#define N_THR 3

double ns=0;
double zs=0;
double moj_pi=0;

int count=0;
double diff=100;
pthread_mutex_t count_mutex;
pthread_cond_t count_cv;



void *watch_count(void *t){
    pthread_mutex_lock(&count_mutex);
    while (diff>=0.0001) {
            pthread_cond_wait(&count_cv, &count_mutex);
            printf("Calculated PI: %f.\n", moj_pi);
    }
    pthread_mutex_unlock(&count_mutex);
    pthread_exit(NULL);
}


void *inc_count(void *t){
    while(diff>=0.0001){
        double x = ((double) rand()) / RAND_MAX;
        double y = ((double) rand()) / RAND_MAX;
        pthread_mutex_lock(&count_mutex);
        ns++;
        if (x*x + y*y <=1){
            zs++;
        }
        moj_pi=4* zs / ns;
        printf("PI: %f\n",moj_pi);
        diff=M_PI - moj_pi;
        if (diff<0)
            diff=0-diff;
        printf("Difference: %f\n",diff);
        if (diff <0.0001){
            pthread_cond_signal(&count_cv);
        }
        pthread_mutex_unlock(&count_mutex);
    }
    pthread_exit(NULL);
}



int main(){
    int i;
    pthread_t id[N_THR];
    pthread_attr_t attr;
    pthread_mutex_init(&count_mutex, NULL);
    pthread_cond_init(&count_cv, NULL);
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    pthread_create(&id[0], &attr, watch_count, (void *)1);
    for (i=1;i<N_THR;i++)
        pthread_create(&id[i], &attr, inc_count, (void *)(i+1));

    for (i=0;i<N_THR;i++)
        pthread_join(id[i], NULL);


    pthread_attr_destroy(&attr);
    pthread_mutex_destroy(&count_mutex);
    pthread_cond_destroy(&count_cv);
    pthread_exit(NULL);
}

最佳答案

您正在从多个线程使用变量diff,而它始终不受互斥体的保护。

此外,正如 rand() 的手册页中所述:

The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call


乍一看,您的问题是,diff 在您循环测试之后以及锁定互斥体之前可能会发生变化。您需要重新考虑一下锁定逻辑以避免这种竞争条件。

关于c - Linux C 中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27234160/

相关文章:

c++ - thread_local "storage class specified"

git - "You' 已成功验证,但 GitHub 不提供 shell 访问” 在运行完所有 ssh 设置步骤后

c++ - 轮询 TCP 套接字空闲监听

ubuntu - VirtualBox - 从主机操作系统创建虚拟机作为克隆

c - 返回指向函数错误的指针

c - 为什么我的 int 变量值突然跳跃?

c - C 中的 float 比较

c++ - 执行 CUDA 程序时出现段错误

swift - 如何使用 AVAudioEngine 在同一时间更改音调和速率

Python 多线程和多处理加速循环