#include#include #include #define THREAD_NUM 5 void *scan_task(void *arg) { long id = (long)arg; printf("ScanTask[%ld] started\n", id); // 掃描邏輯 return NULL; } void *process_task(void *arg) { puts("ProcessTask started"); // 處理邏輯 return NULL; } int main() { pthread_t threads[THREAD_NUM]; pthread_t single; // 批量創建相同邏輯執行緒 for (long i = 0; i < THREAD_NUM; i++) { if (pthread_create(&threads[i], NULL, scan_task, (void*)i) != 0) { perror("pthread_create"); exit(1); } } // 創建單一不同邏輯執行緒 pthread_create(&single, NULL, process_task, NULL); // 關鍵:等待所有執行緒結束 for (int i = 0; i < THREAD_NUM; i++) pthread_join(threads[i], NULL); pthread_join(single, NULL); puts("All threads finished"); return 0; }
gcc -o thread_demo thread_demo.c -lpthread # -lpthread 必須放在源檔後面,鏈結 pthread 庫
int pthread_create(pthread_t *tid, const pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg);
// tid: 輸出執行緒ID
// attr: 屬性 (NULL 用預設)
// start_routine: 入口函數,簽名 void*(*)(void*)
// arg: 傳遞給入口函數的參數
多執行緒同時 g_var++ 非原子,導致資料競爭。解決:pthread_mutex_lock、原子操作、pthread_join 確保順序。
pthread_join 回收資源,避免殭屍執行緒。