gpt4 book ai didi

在 C 中使用 pThread 将数组与多线程进行比较

转载 作者:行者123 更新时间:2023-11-30 14:58:11 27 4
gpt4 key购买 nike

我在理解多线程方面遇到一些困难。情况如下:

我将从一个数组中选择一些整数,并在某些条件下将它们存储到另一个数组中。条件相当复杂,基本上是 array[i] 和所有其他 array[not i] 之间的大量比较。我们称之为 checkCondition();

首先,我创建 pthread。这是我的代码,注意到 dataPackage 是一个包含数组的结构。

for(int i = 0; i < thread_number; i++){
if(pthread_create(&tid, NULL, checkPermissible, &dataPackage) != 0){
perror("Error occurs when creating thread!!!\n");
exit(EXIT_FAILURE);
}
}

for(int i = 0; i < thread_number; i++){
pthread_join(tid, NULL);
}

这是checkPermissible()的内容

void* checkPermissible(void* content){
readThread *dataPackage = content;

for(int i = 0; i < (*dataPackage).arrayLength; i++){
if(checkCondition()){
pthread_mutex_lock(&mutex);
insert(array[i], (*dataPackage).result);
pthread_mutex_unlock(&mutex);
//if condition true, insert it into result(a pointer)
//mutex avoid different thread insert the value at the same time
}
}

pthread_exit(NULL);
}

但是,如果我不使用 pThread 方式来执行此操作,则不会有任何区别。如何实现 checkPermissible() 以发挥多线程的优势?我对这个东西很困惑。

我的想法是,将数组划分为每个Thread中的noOfThread。例如,我有一个数组[20]和4个线程,

Thread 1: compute checkCondition with array[0] to array[4]
Thread 2: compute checkCondition with array[5] to array[9]
Thread 3: compute checkCondition with array[10] to array[14]
Thread 4: compute checkCondition with array[15] to array[19]

类似的东西,我不知道如何实现。

最佳答案

首先,您可以将下限和上限或地址传递给结构中的线程,如下所示:

struct readThread {
int low;
int hi;
int * myarray;
};

for (int i=low;i<hi;++i)

//or

struct readThread {
int * start;
int * end;
};

for (int* i=start; i<end; ++i)

第一个也更容易理解。这样,你的数组就会 split 。

还有其他方法,例如为每个线程创建错误的拆分副本。

关于在 C 中使用 pThread 将数组与多线程进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448579/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com