C 語言多線程與鎖機制
多線程
#include <pthread.h>
void *TrainModelThread(void *id) {
...
pthread_exit(NULL); //線程退出
}
pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t)); //建立 num_threads 個線程
for (a = 0; a < num_threads; a++)
pthread_create(&pt[a], NULL, TrainModelThread, (void *)a); //註冊線程
for (a = 0; a < num_threads; a++)
pthread_join(pt[a], NULL); //線程執行
鎖機制
pthread_mutex_t writable[100]; //lock
pthread_mutex_init(&writable[i], NULL); //鎖的初始化
pthread_mutex_lock(&writable[i]); //加鎖
... //臨界區
pthread_mutex_unlock(&writable[i]); //解鎖