【问题标题】:compare array with multiple thread using pThread in C在 C 中使用 pThread 将数组与多线程进行比较
【发布时间】:2017-04-17 09:18:55
【问题描述】:

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

我将从一个数组中选择一些整数并将它们存储到另一个具有某些条件的数组中。条件相当复杂,基本上是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() 以发挥多线程的优势?我对这个东西很困惑。

我的想法是,在每个线程中将数组分成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]

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

【问题讨论】:

  • checkCondition是cpu密集型操作吗?如果不是这样,您可能根本无法从多线程中受益。
  • 不,不是。使用多线程是必需的,我相信是为了提高速度。
  • 但是有什么问题呢?它有效吗?您的帖子没有明确的问题。
  • checkPermissible() 即使没有创建任何线程也可以。我想知道如何更改实现以发挥多线程的优势。我希望它类似于“每个线程运行 checkCondition (array_length/noOfThread) 次。”
  • 可以工作。然而,这似乎是一个典型的问题,缓存将消除多线程的所有优势。线程将花费大部分时间等待从内存中获取数组数据。

标签: c arrays multithreading pthreads mutex


【解决方案1】:

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

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)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2015-07-29
    • 2019-04-06
    • 2017-05-21
    相关资源
    最近更新 更多