Trong hướng dẫn này, thảo luận hàm luồng (thread functions) trong C/C++.
Thread functions cho phép thực thi các hàm đồng thời (concurrent), có thể phụ thuộc hoặc độc lập lẫn nhau.
Ví dụ
#include#include #include void* func(void* arg){ // tách luồng hiện tại pthread_detach(pthread_self()); printf("Inside the thread\n"); pthread_exit(NULL); } void fun(){ pthread_t ptid; // tạo luồng mới pthread_create(&ptid, NULL, &func, NULL); printf("This line may be printed before thread terminates\n"); if(pthread_equal(ptid, pthread_self())) printf("Threads are equal\n"); else printf("Threads are not equal\n"); // chờ luồng kết thúc pthread_join(ptid, NULL); printf("This line will be printed after thread ends\n"); pthread_exit(NULL); } int main(){ fun(); return 0; }
Kết quả
This line may be printed before thread terminates Threads are not equal Inside the thread This line will be printed after thread ends