在Linux中,pthread(POSIX線程)庫允許你創建和管理線程
pthread_create()
函數創建一個新線程。這個函數需要一個指向pthread_t
類型變量的指針作為返回值,該變量將在成功創建線程時存儲新線程的標識符。#include <pthread.h>
void *thread_function(void *arg);
int main() {
pthread_t thread_id;
int rc;
rc = pthread_create(&thread_id, NULL, thread_function, NULL);
if (rc != 0) {
// 處理錯誤
}
// 其他代碼...
return 0;
}
pthread_join()
函數等待一個或多個線程完成。這個函數需要一個指向pthread_t
類型變量的指針作為參數,該變量表示要等待的線程的標識符。pthread_join()
函數將阻塞調用它的線程,直到被等待的線程結束。#include <pthread.h>
void *thread_function(void *arg);
int main() {
pthread_t thread_id;
int rc;
rc = pthread_create(&thread_id, NULL, thread_function, NULL);
if (rc != 0) {
// 處理錯誤
}
// 等待線程結束
pthread_join(thread_id, NULL);
// 其他代碼...
return 0;
}
pthread_detach()
函數。這個函數需要一個指向pthread_t
類型變量的指針作為參數,該變量表示要分離的線程的標識符。調用pthread_detach()
后,被分離的線程將在完成其執行后立即結束,而不會影響主線程或其他線程。#include <pthread.h>
void *thread_function(void *arg);
int main() {
pthread_t thread_id;
int rc;
rc = pthread_create(&thread_id, NULL, thread_function, NULL);
if (rc != 0) {
// 處理錯誤
}
// 分離線程
pthread_detach(thread_id);
// 其他代碼...
return 0;
}
總之,Linux中的pthread庫允許你創建和管理線程,你可以根據需要選擇等待線程結束、立即結束線程或讓線程在完成后自動分離。