I have a problem. I need to implement a program that switches ucontext threads using a timer and SIGALRM but I am getting a segmentation fault when I switch threads using my evict_thread function. I believe it is the result of a race condition as it occurs at different times durings the programs execution. Here is my evict_thread
void evict_thread(int signal)
{
// Check that there is more than one thread in the queue
if ((int)list_length(runqueue) > 1)
{
// Remove the currently executing thread from the runqueue and store its id
int evict_thread_id = list_shift_int(runqueue);
// Place the thread at the back of the run queue
list_append_int(runqueue, evict_thread_id);
// Get the id of the thread that is now at the head of the run queue
int exec_thread_id = list_item_int(runqueue, 0);
// Set the start time for new thread to the current time
clock_gettime(CLOCK_REALTIME, &thread_table[exec_thread_id]->start);
printf("Switching context from %s to %s\n",
thread_table[evict_thread_id]->thread_name,
thread_table[exec_thread_id]->thread_name);
// Execute the thread at the head of the run queue
if (swapcontext(&thread_table[evict_thread_id]->context, &thread_table[exec_thread_id]->context) == -1)
{
perror("swapcontext failed\n");
printf("errno: %d.\n", errno);
return;
}
}
return;
}
The above function is called in the following manner
// Set the SIGALRM
if (sigset(SIGALRM, evict_thread) == -1)
{
perror("sigset failed\n");
printf("errno: %d.\n", errno);
return;
}
// Initialize timer
thread_switcher.it_interval.tv_sec = 0;
thread_switcher.it_interval.tv_usec = quantum_size;
thread_switcher.it_value.tv_sec = 0;
thread_switcher.it_value.tv_usec = quantum_size;
setitimer(ITIMER_REAL, &thread_switcher, 0);
The run queue is simply a global list of integers that are indices into a global table of pointers to the ucontext threads. The list is implemented using the list data structure from a C general utility library available at libslack.org
When I disable the timer and let each thread run to completion before switching contexts the program runs properly, but when the threads are switched during execution I get a segmentation fault around 80% of the time.
Also when I attempt to use gdb to backtrace the segmentation fault its says that it occurs within a systemcall.