@MuffinLover

Почему не печатается?

Почему не печатается "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;
}
  • Вопрос задан
  • 199 просмотров
Решения вопроса 1
jcmvbkbc
@jcmvbkbc
"I'm here to consult you" © Dogbert
Почему не печатается "custom thread completed"

Потому что thread->context.uc_link = NULL; в строке 27, а, согласно man swapcontext:
If the successor context pointer is NULL, the thread exits.


Исправить можно, например, так:
int custom_thread_create(custom_thread *thread, ucontext_t *link, void (*start_routine)(void*), void *arg) {
    …
    thread->context.uc_link = link;
    …
}
…
    ucontext_t main_context;
    getcontext(&main_context);

    if (custom_thread_create(&thread, &main_context, print_message, (void*)message) == 0) {
…
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы