简体   繁体   English

为什么 pthread_join() 返回 0 而不是我线程的返回值?

[英]Why is pthread_join() returning 0 instead of the return value from my thread?

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".我正在尝试创建一个多线程程序,该程序将从与可执行文件相同的目录中逐行搜索短语“Hello World”的 substring 的多个文件。 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.不幸的是,第一个线程返回 0 读取的模式数量而不是正确的值,而所有其他后续线程都返回正确的值。 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?我是否误解了pthread_join()的工作方式?

 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. &a是一个局部变量的地址,一个在searchfile()返回时被销毁的变量。 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() .这可能是全局变量或 static 变量,也可能是从主线程传入的指针,也可能是使用malloc()分配的堆 memory。 If you do the last then the main thread ought to free() it once it's done with it.如果你做最后一个,那么主线程应该在它完成后free()它。

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

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

...

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

...

return threadPatterns;

You can look into pthread_exit() to return any value from thread.您可以查看 pthread_exit() 以从线程返回任何值。 However if you want to return some value from pthread.join() you can make use of global variables.但是,如果您想从 pthread.join() 返回一些值,您可以使用全局变量。 Man Page for pthread_join pthread_join 的手册页

Understanding pthread_exit 了解 pthread_exit

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

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