我想在C中使用pthread來比較兩個字符串。這個想法是看看完整的字符串2是否在字符串1中(例如,如果string1 = lkajdsgl
和string2 = jd
然後我會有一個匹配)。我不明白的是pthread如何以一般方式工作。這裏我創建我的pthreads,假設爲NUM_THREADS=3
,那麼我應該有3個線程,線程[0],線程[1]和線程[2]。每個將調用Pthrd_Substring函數。字符串將從文件讀入並在函數中分析。但是,我不明白的是如何使用pthread_join
。如果字符串長度爲12個字符,並且我只有3個線程,系統知道如何繼續使用3個線程分析字符串,直到檢查完所有12個字符爲止? (函數看起來在串1中的每個字母以及確定所述完整的字符串2是本之前它與串2的第一個字母進行比較。)試圖瞭解pthread如何在C工作
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int count, rc;
long t;
for(t=0;t<NUM_THREADS;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, Pthrd_Substring, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
printf("The number of substrings is: %d\n", count);
return 1;
}
我可以使用類似:
pthread_join(threads0, NULL);
partial_sum += t.partial_count;
pthread_join(threads1, NULL);
partial_sum += t.partial_count;
pthread_join(threads2, NULL);
partial_sum += t.partial_count;
並且在函數中擁有全局總數?但是,這是否會讓字符串中的每個字母都被檢查?
我是猶豫包括這部分,因爲我還沒有制定這一切了,因爲我不明白的並行線程調用怎麼工作的主。然而,這是僞代碼,我有一個功能,在這裏n1
是string1
和n2
字符串長度的string2
的長度:
void *Pthrd_Substring(void *thrdptr)
{
int i,j,k;
int count;
int total = 0;
for (i = thrdptr; i <= (n1-n2); i++){
count=0;
for(j = i,k = 0; k < n2; j++,k++){ /*search for the next string of size of n2*/
if (*(s1+j)!=*(s2+k)){
break;
}
else
count++;
if(count==n2)
total++; /*find a substring in this step*/
}
}
partial_count = total
}
請顯示'Pthrd_Substring'。實際上請確保提供[mcve]。 – kaylum
我希望能提供所需的信息。代碼不完整,因爲我沒有解決這個問題。 – Joseph
誰的想法是使用多個線程進行子字符串搜索?正如我能想到的那樣,這是一個奇怪的想法。如果這不是一個有點虐待老師對作業練習的看法,那麼你應該避免這樣做。你的'Pthrd_Substring()'函數不會像所示的那樣乾淨地編譯('i = thrdptr')。它使用你沒有顯示的全局變量('n1','n2')。你有很多重大問題。你將一個指向't'的指針傳遞給所有線程,但是你不能確保每個線程都能看到它自己的數據。你不知道每個線程用作值。 –