在C语言中,可以使用pthread库来进行多线程编程。以下是一个简单的多线程程序示例:
#include <stdio.h>#include <pthread.h>#define NUM_THREADS 5// 线程函数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;// 创建多个线程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;}}// 等待所有线程结束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函数中创建了多个线程。pthread_create函数用于创建线程,它接受四个参数:指向线程标识符的指针,线程属性(通常设置为NULL),指向线程函数的指针,以及传递给线程函数的参数。
然后使用pthread_join函数等待线程的结束。pthread_join函数用于挂起调用它的线程,直到指定的线程终止。它接受两个参数:要等待的线程标识符和指向线程返回值的指针(在本例中使用NULL)。
注意:使用多线程编程时,需要注意线程之间的同步和互斥问题,以避免竞态条件和数据访问冲突。