C++ 两次调用pthread_join()时glibc pthread_join崩溃
我使用POSIX pthread库编写了以下代码:C++ 两次调用pthread_join()时glibc pthread_join崩溃,c++,linux,multithreading,pthread-join,C++,Linux,Multithreading,Pthread Join,我使用POSIX pthread库编写了以下代码: #include <stdlib.h> #include <pthread.h> void *thread_function(void *arg) { char *code = "1"; } int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_create(&a_thread, NULL, thre
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg) {
char *code = "1";
}
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if (res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
sleep(5);
printf("\nWaiting for thread to finish...\n");
res = pthread_join(a_thread, &thread_result);
printf("res[%d]\n",res);
if (res != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
}
res = pthread_join(a_thread, &thread_result);
printf("res[%d]\n",res);
exit(EXIT_SUCCESS);
}
在代码中,我想测试如果调用pthread_jion()函数会发生什么
线程完成后两次。第一次调用函数是正确的,第二次崩溃。回溯:
Core was generated by `./a.out'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 pthread_join (threadid=140150565050112, thread_return=0x7fffa0a2c508) at
pthread_join.c:47
47 if (INVALID_NOT_TERMINATED_TD_P (pd))
(gdb) bt
Python Exception exceptions.ImportError No module named gdb.frames:
#0 pthread_join (threadid=140150565050112, thread_return=0x7fffa0a2c508) at
pthread_join.c:47
#1 0x00000000004008d5 in main ()
我检查pthread_join.c文件:
39 int
40 pthread_join (threadid, thread_return)
41 pthread_t threadid;
42 void **thread_return;
43 {
44 struct pthread *pd = (struct pthread *) threadid;
45
46 /* Make sure the descriptor is valid. */
47 if (INVALID_NOT_TERMINATED_TD_P (pd))
48 /* Not a valid thread handle. */
49 return ESRCH;
在第47行中,宏定义检查pd是否为有效的线程句柄。如果不是,则返回ESRCH(3)
但是,当我在另一个Linux环境中运行相同的代码时,我得到了以下输出:
Waiting for thread to finish...
res[0]
Segmentation fault (core dumped)
Waiting for thread to finish...
res[0]
res[3]
这与环境有关吗?两个linux系统具有相同的ldd版本:
ldd (GNU libc) 2.17
同样的GLIBC:
GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
GLIBCXX_3.4.3
GLIBCXX_3.4.4
GLIBCXX_3.4.5
GLIBCXX_3.4.6
GLIBCXX_3.4.7
GLIBCXX_3.4.8
GLIBCXX_3.4.9
GLIBCXX_3.4.10
GLIBCXX_3.4.11
GLIBCXX_3.4.12
GLIBCXX_3.4.13
GLIBCXX_3.4.14
GLIBCXX_3.4.15
GLIBCXX_3.4.16
GLIBCXX_3.4.17
GLIBCXX_3.4.18
GLIBCXX_3.4.19
GLIBCXX_3.4.20
GLIBC_2.3
GLIBC_2.2.5
GLIBC_2.14
GLIBC_2.17
GLIBC_2.3.2
GLIBCXX_FORCE_NEW
GLIBCXX_DEBUG_MESSAGE_LENGT
和相同的linux内核版本:
Red Hat Enterprise Linux Server release 6.6 (Santiago)
pthread\u join
在线程终止后调用pthread\u detach
。
pthread\u detach
在线程终止时释放所有线程资源
从pthread\u detach
尝试分离已分离的线程会导致
未指明的行为
所以你有未指明的行为,所以你不能保证以后会发生什么
至少,threadid
指向的内存将被释放,从而访问释放的内存
简而言之,不要在同一个threadid上调用两次pthread\u join
。你为什么要这么做
编辑:甚至更简单:pthread\u join
的手册页上说:
与先前已连接的螺纹连接会导致
未定义的行为