Skip to content

Instantly share code, notes, and snippets.

@0x1306a94
Last active July 24, 2022 03:11
Show Gist options
  • Save 0x1306a94/327a108f8f912269c2c65d2a46e3b477 to your computer and use it in GitHub Desktop.
Save 0x1306a94/327a108f8f912269c2c65d2a46e3b477 to your computer and use it in GitHub Desktop.
pthread test
//
// main.c
// testdadkajdkajf
//
// Created by king on 2022/7/22.
//
#include <pthread.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define SafeFree(ptr) \
do { \
if (ptr != NULL) { \
free(ptr); \
ptr = NULL; \
} \
} while (0);
typedef struct {
jmp_buf env;
size_t num;
char *argv[0];
} ThreadArg;
pthread_key_t p_key;
static void exit_thread(void) {
void *user_data = pthread_getspecific(p_key);
if (user_data == NULL) {
pthread_exit(NULL);
return;
}
ThreadArg *arg = (ThreadArg *)user_data;
longjmp(arg->env, 1);
return;
}
static void exec_cleanup(void *user_data) {
printf("work thread cleanup\n");
ThreadArg *arg = (ThreadArg *)user_data;
for (int i = 0; i < arg->num; i++) {
SafeFree(arg->argv[i]);
}
SafeFree(arg);
return;
}
static void *exec_fn(void *user_data) {
printf("work thread end\n");
pthread_cleanup_push(exec_cleanup, user_data);
pthread_setspecific(p_key, user_data);
ThreadArg *arg = (ThreadArg *)user_data;
int res = setjmp(arg->env);
if (res == 0) {
usleep(100);
for (int i = 0; i < arg->num; i++) {
if (i == 3) {
exit_thread();
}
printf("%s\n", arg->argv[i]);
}
}
pthread_cleanup_pop(res);
printf("work thread exit\n");
return (void *)0;
}
int main(int argc, const char *argv[]) {
printf("main thread start\n");
pthread_key_create(&p_key, NULL);
ThreadArg *arg = malloc(sizeof(ThreadArg) + sizeof(char *) * argc);
arg->num = argc;
for (int i = 0; i < argc; i++) {
arg->argv[i] = NULL;
// arg->argv[i] = strdup(argv[i]);
}
pthread_t tid;
pthread_create(&tid, NULL, exec_fn, (void *)arg);
pthread_join(tid, NULL);
printf("main thread end\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment