溫馨提示×

c語言多線程庫怎么調(diào)用

小億
106
2023-09-20 21:28:40
欄目: 編程語言

在C語言中,可以使用pthread庫來進行多線程編程。以下是一個簡單的多線程程序示例:

#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 5
// 線程函數(shù)
void* threadFunction(void* threadId) {
long tid = (long)threadId;
printf("Hello from thread %ld\n", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
// 創(chuàng)建多個線程
for (t = 0; t < NUM_THREADS; t++) {
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, threadFunction, (void*)t);
if (rc) {
printf("ERROR: return code from pthread_create() is %d\n", rc);
return 1;
}
}
// 等待所有線程結(jié)束
for (t = 0; t < NUM_THREADS; t++) {
rc = pthread_join(threads[t], NULL);
if (rc) {
printf("ERROR: return code from pthread_join() is %d\n", rc);
return 1;
}
}
printf("All threads have completed successfully.\n");
return 0;
}

在上述代碼中,首先包含了pthread.h頭文件,然后在main函數(shù)中創(chuàng)建了多個線程。pthread_create函數(shù)用于創(chuàng)建線程,它接受四個參數(shù):指向線程標(biāo)識符的指針,線程屬性(通常設(shè)置為NULL),指向線程函數(shù)的指針,以及傳遞給線程函數(shù)的參數(shù)。

然后使用pthread_join函數(shù)等待線程的結(jié)束。pthread_join函數(shù)用于掛起調(diào)用它的線程,直到指定的線程終止。它接受兩個參數(shù):要等待的線程標(biāo)識符和指向線程返回值的指針(在本例中使用NULL)。

注意:使用多線程編程時,需要注意線程之間的同步和互斥問題,以避免競態(tài)條件和數(shù)據(jù)訪問沖突。

0