Почему не печатается "custom thread completed"
#include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
#include <signal.h>
typedef struct {
ucontext_t context;
void (*start_routine)(void*);
void *arg;
int is_completed;
} custom_thread;
void custom_thread_start(void *args) {
custom_thread* thread = (custom_thread*)args;
thread->start_routine(thread->arg);
thread->is_completed = 1;
// Switch back to the main thread
swapcontext(&thread->context, thread->context.uc_link);
}
int custom_thread_create(custom_thread *thread, void (*start_routine)(void*), void *arg) {
getcontext(&thread->context);
thread->context.uc_stack.ss_sp = malloc(SIGSTKSZ);
thread->context.uc_stack.ss_size = SIGSTKSZ;
thread->context.uc_link = NULL;
thread->start_routine = start_routine;
thread->arg = arg;
thread->is_completed = 0;
makecontext(&thread->context, (void (*)(void))custom_thread_start, 1, thread);
return 0; // success
}
// Test example
void print_message(void* message) {
char* msg = (char*)message;
printf("Thread message: %s\n", msg);
}
int main() {
custom_thread thread;
char message[] = "Hello, custom thread!";
if (custom_thread_create(&thread, print_message, (void*)message) == 0) {
printf("Custom thread created successfully...\n");
} else {
printf("Failed to create custom thread...\n");
return -1;
}
// Save the current context to switch back later
ucontext_t main_context;
getcontext(&main_context);
if (!thread.is_completed) {
// Switch to the custom thread
swapcontext(&main_context, &thread.context);
}
printf("Custom thread completed...\n");
// Clean up the custom thread's stack
free(thread.context.uc_stack.ss_sp);
return 0;
}