繁体   English   中英

在C中使用pThread比较具有多个线程的数组

[英]compare array with multiple thread using pThread in C

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

我将从一个数组中选择一些整数,并在某些条件下将它们存储到另一个数组中。 条件非常复杂,基本上,这是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。 例如,我有一个array [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)

第一个也越来越容易理解。 这样,您的阵列将分裂。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM