Wagmi React 类型系统实战:TypeScript 要求、Register 声明合并与 const-Asserted ABI 类型推断
2026/9/17 6:00:33
pthread_create函数。pthread_join或设置分离属性回收资源(避免内存泄漏)。在 Linux 终端,可使用以下命令查看线程:
ps -eLf # 显示进程和线程信息 ps -elf # 详细列表下面逐一解释您列出的函数,并提供代码示例。所有示例基于 C 语言,使用 POSIX 线程库。
获取线程 ID (pthread_t pthread_self(void))
pthread_t类型,通常为unsigned long)。#include <stdio.h> #include <pthread.h> void *thread_func(void *arg) { pthread_t tid = pthread_self(); printf("Thread ID: %lu\n", (unsigned long)tid); pthread_exit(NULL); } int main() { pthread_t tid; pthread_create(&tid, NULL, thread_func, NULL); pthread_join(tid, NULL); return 0; }线程退出 (void pthread_exit(void *retval))
retval为退出状态指针(可自定义数据类型)。#include <stdio.h> #include <pthread.h> void *thread_func(void *arg) { printf("Thread exiting...\n"); int *status = malloc(sizeof(int)); *status = 42; // 自定义退出状态 pthread_exit(status); } int main() { pthread_t tid; void *retval; pthread_create(&tid, NULL, thread_func, NULL); pthread_join(tid, &retval); printf("Thread exit status: %d\n", *(int *)retval); free(retval); return 0; }请求结束线程 (int pthread_cancel(pthread_t thread))
thread为目标线程 ID。#include <stdio.h> #include <pthread.h> #include <unistd.h> void *thread_func(void *arg) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); while(1) { printf("Thread running...\n"); sleep(1); } pthread_exit(NULL); } int main() { pthread_t tid; pthread_create(&tid, NULL, thread_func, NULL); sleep(3); // 等待 3 秒后取消线程 pthread_cancel(tid); pthread_join(tid, NULL); printf("Thread canceled.\n"); return 0; }线程资源回收 (int pthread_join(pthread_t thread, void **retval))
thread:目标线程 ID。retval:接收线程退出状态(需匹配pthread_exit的返回值)。pthread_exit示例。设置分离属性 (int pthread_detach(pthread_t thread))
pthread_join)。thread为目标线程 ID(通常线程自身调用)。#include <stdio.h> #include <pthread.h> void *thread_func(void *arg) { pthread_detach(pthread_self()); // 设置自身为分离状态 printf("Detached thread running.\n"); pthread_exit(NULL); } int main() { pthread_t tid; pthread_create(&tid, NULL, thread_func, NULL); sleep(1); // 主线程短暂等待 printf("Main thread continues.\n"); return 0; // 分离线程资源由系统回收 }以下程序展示创建多个线程、使用共享资源,并回收资源:
#include <stdio.h> #include <pthread.h> #define NUM_THREADS 3 void *worker(void *arg) { int thread_num = *(int *)arg; printf("Thread %d started. ID: %lu\n", thread_num, (unsigned long)pthread_self()); pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; int thread_args[NUM_THREADS]; // 创建线程 for (int i = 0; i < NUM_THREADS; i++) { thread_args[i] = i; if (pthread_create(&threads[i], NULL, worker, &thread_args[i]) != 0) { perror("pthread_create error"); return 1; } } // 回收线程资源 for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf("All threads completed.\n"); return 0; }pthread_join或设置分离属性)。pthread_mutex)防止竞态条件。perror或strerror诊断错!