在Linux中,使用POSIX線程(pthread)庫時,線程的初始化是通過調用pthread_create()
函數來完成的
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *my_thread_function(void *arg) {
printf("Hello from the new thread!\n");
return NULL;
}
int main() {
pthread_t thread_id;
int rc;
// 初始化線程
rc = pthread_create(&thread_id, NULL, my_thread_function, NULL);
if (rc != 0) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
// 在此處執行主線程的其他任務
// 等待子線程完成
pthread_join(thread_id, NULL);
return 0;
}
在這個示例中,我們創建了一個名為my_thread_function
的線程函數,然后在main()
函數中使用pthread_create()
初始化并運行這個線程。當pthread_create()
成功執行時,它將返回0,并將新線程的ID存儲在thread_id
變量中。