我可以在 C 上的相同函数上使用 pthreads 吗?

Can I use pthreads over the same function on C?

我怀疑他们可能是傻子。我有一个计算一些数学公式的函数作为例子。

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


pthread_mutex_t a_mutex = PTHREAD_MUTEX_INITIALIZER;
volatile long int a = 0;


void threadOne(void *arg) 
{


 int i;
    long int localA = 0;

    for (i = 1; i < 50000000; i++) 
    {
     localA = localA + i*a*sqrt(a);
    }

    pthread_mutex_lock(&a_mutex);
    a = a + localA;
    pthread_mutex_unlock(&a_mutex);
}


void threadTwo(void *arg) 
{
    int i;
    long int localA = 0;
    for (i = 50000000; i <= 100000000; i++)
    {
     localA = localA + i*a*sqrt(a);
    }
   pthread_mutex_lock(&a_mutex);
   a = a + localA;
   pthread_mutex_unlock(&a_mutex);
}


int main (int argc, char **argv) 
{
    pthread_t one, two;
    int i;
    pthread_create(&one, NULL, (void*)&threadOne, NULL);
    pthread_create(&two, NULL, (void*)&threadTwo, NULL);
    pthread_join(one, NULL);
    pthread_join(two, NULL);
}

现在这是我找到的一个例子,我有两个函数,每个函数都有一个线程,所以一个是在不同的线程上计算的。但是我可以只有一个函数,然后有两个线程到一个函数,所以函数 运行s 两次使用不同的数据吗?我的想法是这样的:我只有一个函数可以有两组不同的数据,然后函数可以 运行 与第一组或第二组取决于线程是 运行ning。

但这可能吗?。我想避免像这里那样复制函数两次。

让我们说我只保留功能

void threadOne(void *arg)

但是我 运行 它两次使用不同的线程同时处理不同的数据,这是可以实现的还是我只是在犯傻?

是的,这可以通过使用线程函数的参数来完成。

每个线程都需要遍历一定范围的值。所以创建一个结构定义来包含最小值和最大值:

struct args {
    int min;
    int max;
};

定义一个单线程函数,它将 void * 参数转换为指向该类型的指针并读取它:

void *thread_func(void *arg) 
{
    struct args *myargs = arg;
    int i;
    long int localA = 0;
    for (i = myargs->min; i < myargs->max; i++) 
    {
        localA = localA + i*a*sqrt(a);
    }
    pthread_mutex_lock(&a_mutex);
    a = a + localA;
    pthread_mutex_unlock(&a_mutex);
    return NULL;
}

(注意函数需要return一个void *来符合pthread_create期望的接口。)

然后在您的 main 函数中为每组参数创建该结构的一个实例,并将其传递给 pthread_create:

int main (int argc, char **argv) 
{
    pthread_t one, two;
    struct args args1 = { 1, 50000000 };
    struct args args2 = { 50000000 , 100000000 };
    pthread_create(&one, NULL, thread_func, &args1);
    pthread_create(&two, NULL, thread_func, &args2);
    pthread_join(one, NULL);
    pthread_join(two, NULL);
}