在Linux下,使用C语言可以通过`getpid()`函数来获取当前进程的ID,使用`pthread_self()`函数获取当前线程的ID。主线程的线程ID可以通过`pthread_self()`函数获取。以下是一个简单的示例代码:
c
#include
#include
#include
void* thread_function(void* arg) {
pthread_t tid = pthread_self();
printf("Thread ID: %lu\n", (unsigned long)tid);
return NULL;
}
int main() {
pthread_t main_tid = pthread_self();
printf("Main Thread ID: %lu\n", (unsigned long)main_tid);
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
pthread_join(thread, NULL);
return 0;
}
在这个代码中,`pthread_self()`用于获取当前线程的ID。在主线程中调用它,将输出主线程的ID。在新的线程中调用同样的函数以输出新线程的ID。
注意,线程ID可能会是一个较大的数值,类型为`pthread_t`,在打印时通常转换为`unsigned long`类型以便输出。
如果只是想要获取主线程的线程ID,直接在`main()`函数中调用`pthread_self()`即可。
查看详情
查看详情