Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

pthread_self() ใน C


ที่นี่เราจะดูว่า pthread_self() มีผลกระทบอย่างไรใน C. ฟังก์ชัน pthread_self() ใช้เพื่อรับ ID ของเธรดปัจจุบัน ฟังก์ชันนี้สามารถระบุเธรดที่มีอยู่ได้โดยไม่ซ้ำกัน แต่ถ้ามีหลายเธรดและหนึ่งเธรดเสร็จสมบูรณ์ id นั้นก็สามารถนำมาใช้ซ้ำได้ ดังนั้นสำหรับเธรดที่รันอยู่ทั้งหมด รหัสจึงไม่ซ้ำกัน

ตัวอย่าง

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* func(void* p) {
   printf("From the function, the thread id = %d\n", pthread_self()); //get current thread id
      pthread_exit(NULL);
   return NULL;
}
main() {
   pthread_t thread; // declare thread
   pthread_create(&thread, NULL, func, NULL);
   printf("From the main function, the thread id = %d\n", thread);
   pthread_join(thread, NULL); //join with main thread
}

ผลลัพธ์

From the main function, the thread id = 1
From the function, the thread id = 1