溫馨提示×

Linux多線程怎么創(chuàng)建

小億
109
2023-08-16 10:20:42

在Linux中,可以使用pthread庫來創(chuàng)建多線程。下面是一個簡單的例子:

#include <stdio.h>
#include <pthread.h>
// 線程函數(shù)
void *thread_func(void *arg) {
int thread_num = *((int*)arg);
printf("Hello from thread %d\n", thread_num);
pthread_exit(NULL);
}
int main() {
pthread_t thread1, thread2; // 兩個線程
int thread1_num = 1;
int thread2_num = 2;
// 創(chuàng)建線程1
pthread_create(&thread1, NULL, thread_func, (void*)&thread1_num);
// 創(chuàng)建線程2
pthread_create(&thread2, NULL, thread_func, (void*)&thread2_num);
// 等待線程1結(jié)束
pthread_join(thread1, NULL);
// 等待線程2結(jié)束
pthread_join(thread2, NULL);
return 0;
}

在這個例子中,我們創(chuàng)建了兩個線程,每個線程都會調(diào)用thread_func函數(shù)。pthread_create函數(shù)用于創(chuàng)建線程,它接受四個參數(shù):線程的標(biāo)識符、線程的屬性、線程函數(shù)、傳遞給線程函數(shù)的參數(shù)。pthread_join函數(shù)用于等待線程結(jié)束。

編譯并運(yùn)行這個程序后,你應(yīng)該可以看到類似以下的輸出:

Hello from thread 1
Hello from thread 2

0