I am trying to use pthread in C to compare two strings. The idea is to see if the complete string 2 is in string 1 (For Example, if string1 = lkajdsgl
and string2 = jd
then I would have one match). What I don't understand is how the pthread works in a general manner. Here I am creating my pthreads, assuming NUM_THREADS=3
, then I should have 3 threads, threads[0], threads[1], and threads[2]. Each will call on the Pthrd_Substring function. The strings will be read in from a file and analyzed in the function. However, what I don't understand is how to use pthread_join
. If the string is 12 characters long and I only have 3 threads how does the system know to keep analyzing the string with the 3 threads until all 12 characters have been examined? (The function looks at each letter in string 1 and compares it with the first letter in string 2 before determining if the full string 2 is present.)
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;
}
I can use something like:
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;
And have a global total in the function? But, does this somehow get every letter in the string examined?
I was hesitant to include this part because I haven't worked it all out since I don't understand how the pthread call works exactly in the main. However, this is the pseudo-code I have for the function, here n1
is the string length of string1
and n2
is the lenght of 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
}
If the string is 12 characters long and I only have 3 threads how does the system know to keep analyzing the string with the 3 threads until all 12 characters have been examined?
The system doesn't know that - just like with non-threaded programming. If you want every character to be analyzed then you need to write your program so it analyzes every character.
However, what I don't understand is how to use pthread_join.
pthread_join
just waits for a thread to exit. That's all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.