更新 3
最近,我注意到我的代码随机导致分段错误错误。但我认为到目前为止我的代码非常简单,我无法弄清楚该错误来自哪里。由于它是随机发生的,我假设存在某种竞争条件。我认为这是所有可能相关的代码,如果您需要更多,请告诉我:
namespace thread {
pthread_t terminated_thread_id, /* and others */;
pthread_mutex_t terminate_thread = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t terminate_thread_signal = PTHREAD_COND_INITIALIZER;
int total_thread_count = 0;
int termination; // + sembufs
inline void* Exit(void* value) {
// This must be unlocked after all join-related jobs are done
semop(thread::termination, thread::termination_in_process, 2)
pthread_mutex_lock(&thread::terminate_thread);
thread::terminated_thread_id = pthread_self();
pthread_cond_signal(&thread::terminate_thread_signal);
pthread_mutex_unlock(&thread::terminate_thread);
pthread_exit(value);
return value;
}
}
int main(int argc, const char** argv){
...
pthread_mutex_lock(&thread::terminate_thread);
if(0 != pthread_create(&thread::communication_handler_thread_id, NULL, \
CommunicationHandler, NULL)){
global::PrintDebug("pthread_create() failed", __FILE__, __LINE__);
}
/** 2 more pthread_create()-calls */
do{
thread::terminated_thread_id = pthread_self();
pthread_cond_wait(&thread::terminate_thread_signal, \
&thread::terminate_thread);
if(!pthread_equal(thread::terminated_thread_id, pthread_self())){
pthread_join(thread::terminated_thread_id, NULL);
...
semop(thread::termination, thread::termination_done, 1)
}
}while(thread::total_thread_count > 0);
pthread_mutex_unlock(&thread::terminate_thread);
return 0;
}
信号terminate_thread_signal仅在thread::Exit()函数中发出。该函数也仅在用于创建线程的函数结束时调用。
这是调试器为调用堆栈显示的内容:
#0 ( 0xb7fe2424 in __kernel_vsyscall() (??:??)
#1 0xb7fbdfcf __pthread_cond_wait(cond=0x80539c0, mutex=0x8053998) (pthread_cond_wait.c:153)
#2 0x804a094 main(argc=1, argv=0xbffff9c4) (/home/papergay/SeekYourCar/0.2/Server/main.cpp:121)
我已经知道的是,如果发生错误,那么还没有线程调用 thread::Exit()。我还使用了一个未命名的命名空间和一些初始化(如果可能相关的话)。我使用 Code::Blocks 作为 IDE 和 GCC 作为编译器。