[英]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.