Skip to content

Commit d8e4e90

Browse files
committed
mb2hal: wait for threads to stop before deallocating the memory they're using
This fixes a shutdown-time race condition in mb2hal between the main thread and the per-link threads. The main thread connects to all the Modbus interfaces and allocates all HAL data structures, then starts a worker thread for each modbus link. The main thread and the worker threads all watch a "time to shutdown" status variable, which is set by a shutdown signal handler. When the "time to shutdown" variable gets set, the per-link threads all exit and the main thread closes down the modbus communications and deallocates the HAL memory. But there was no synchronization between the shutdown of the main thread and the shutdown of the worker threads, so sometimes the worker threads were still accessing the stuff that the main thread was freeing, leading to segfaults. This commit makes the main thread join the worker threads before deallocating anything.
1 parent 9df9b64 commit d8e4e90

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

src/hal/user_comps/mb2hal/mb2hal.c

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,6 @@ int main(int argc, char **argv)
9191

9292
/* Each link has it's own thread */
9393
pthread_attr_init(&thrd_attr);
94-
pthread_attr_setdetachstate(&thrd_attr, PTHREAD_CREATE_DETACHED);
9594
for (counter = 0; counter < gbl.tot_mb_links; counter++) {
9695
ret = pthread_create(&gbl.mb_links[counter].thrd, &thrd_attr, link_loop_and_logic, (void *) &gbl.mb_links[counter].mb_link_num);
9796
if (ret != 0) {
@@ -105,6 +104,14 @@ int main(int argc, char **argv)
105104
sleep(1);
106105
}
107106

107+
for (counter = 0; counter < gbl.tot_mb_links; counter++) {
108+
ret = pthread_join(gbl.mb_links[counter].thrd, NULL);
109+
if (ret != 0) {
110+
ERR(gbl.init_dbg, "Unable to join thread for link number %d: %s", counter, strerror(ret));
111+
}
112+
// OK(gbl.init_dbg, "Link thread %d joined OK OK", counter);
113+
}
114+
108115
QUIT_CLEANUP:
109116
quit_cleanup();
110117
OK(gbl.init_dbg, "going to exit!");

0 commit comments

Comments
 (0)