1

I am trying to create a multithreaded program that will search multiple files from the same directory as the executable line by line for a substring of the phrase "Hello World". Each file is handled by a separate thread.

Unfortunately, the first thread returns 0 for the amount of patterns that are read instead of the correct value, while all other following threads return the correct value. Internally, the thread would show the correct amount of patterns found even for the first thread that returns the wrong value. I just don't understanding why it's returning the incorrect value. Have I misunderstood the way pthread_join() works?

CodeCumber
  • 45
  • 5

2 Answers2

2
int *threadPatterns;
int a = 0;
threadPatterns = &a;

...

return (void *)threadPatterns;

&a is the address of a local variable, a variable which is destroyed when searchfile() returns. After the thread ends that address is no longer valid and accessing it invokes undefined behavior.

To fix it, return an address that will exist after the thread ends. That could be a global or static variable, or it could be a pointer that's passed in from the main thread, or it could be heap memory allocated with malloc(). If you do the last then the main thread ought to free() it once it's done with it.

int *threadPatterns = malloc(sizeof(int));

if (!threadPatterns) {
    // handle allocation failure
}

...

while (...) {
    if(strP) {
        cout << carg << ": " << readLine;
        (*threadPatterns)++;
    }
}

...

return threadPatterns;
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

You can look into pthread_exit() to return any value from thread. However if you want to return some value from pthread.join() you can make use of global variables. Man Page for pthread_join

Understanding pthread_exit

boss
  • 11
  • 1
  • 1
    The return value of the function passed to `pthread_create` is generally good enough. In both cases it should be a pointer to an object whose lifetime is outside the scope of the function, but `pthread_exit` is akin to bailing out of the program with `exit`, the reader and the programmers that use that code won't expect that in most cases. – Oppen Apr 23 '20 at 03:05
  • One can also return a value from a thread by `return`ing it from the thread function, as the OP in fact does. The main thing `pthread_exit()` provides is the ability to terminate the thread from other functions that the thread function calls. Whichever of those means is exercised to terminate a thread, the provided `void *` value is then available from the corresponding `pthread_join()` call. Global variables are generally a poor choice, but they are especially bad in multithreaded programs. – John Bollinger Apr 23 '20 at 03:34