#include<stdio.h> #include<pthread.h> #include<string.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> void printid(char *); void *thr_fn(void *arg) { //todo printid(arg); return NULL; } void printid(char *tip) { pid_t pid = getpid(); pthread_t tid = pthread_self(); printf("%s pid: %u tid:%u (%p)\n", tip, pid, tid, tid); // printf("%s thr_fn=%p\n", tip, thr_fn); } int main(){ pthread_t tid; int ret = pthread_create(&tid, NULL, thr_fn, "new thread"); if (ret) { printf("create thread err:%s\n", strerror(ret)); exit(1); } sleep(1); printid("main thread"); return 0; }
时间: 2024-04-18 08:28:16 浏览: 32
这段代码是一个简单的多线程程序,使用了 pthread 库来创建和管理线程。它包含了一个主线程(main thread)和一个新线程(new thread),并且在每个线程中打印出进程ID(pid)、线程ID(tid)和线程函数的地址。
首先,在代码的开头包含了一些头文件,如 stdio.h、pthread.h、string.h、stdlib.h、unistd.h 和 sys/types.h,这些头文件提供了程序所需的函数和类型声明。
接下来,定义了一个名为 `printid` 的函数,用于打印进程ID、线程ID和线程函数地址等信息。它接受一个字符串作为参数(tip),用于标识是哪个线程调用了该函数。
然后,定义了一个名为 `thr_fn` 的线程函数,它是新线程要执行的函数。在这个函数中,调用 `printid` 函数来打印出新线程的相关信息。
在 `main` 函数中,首先声明了一个 pthread_t 类型的变量 `tid`,用于存储新创建的线程的标识符。
然后,调用 `pthread_create` 函数创建新线程。该函数接受四个参数:新线程的标识符指针、线程属性(这里为 NULL)、线程函数的地址(即 `thr_fn`)和传递给线程函数的参数(这里是一个字符串 "new thread")。
如果 `pthread_create` 函数返回值非零,则表示创建线程失败,打印出错误信息并退出程序。
接着,主线程调用 `sleep` 函数等待一秒钟,以确保新线程有足够的时间执行。
最后,主线程调用 `printid` 函数,打印出主线程的相关信息。
整个程序执行完毕后,返回 0 表示正常退出。