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



我怀疑这可能是愚蠢的家伙。我正在用一个函数来计算一些数学公式作为例子。

# 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);
}

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

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

假设我只保留函数

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;
}

(注意该函数需要返回一个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);
}

最新更新