在C语言中,通过pthread_create()
函数创建一个线程时,需要传递一个指向函数的指针作为第一个参数,该函数称为线程入口函数
#include#include #include // 线程入口函数 void *my_thread(void *arg) { int *num = (int *)arg; // 从参数中获取整数 printf("Hello from thread %d\n", *num); return NULL; } int main() { pthread_t thread1, thread2; int num1 = 1, num2 = 2; // 使用参数创建线程 if (pthread_create(&thread1, NULL, my_thread, (void *)&num1) != 0) { perror("Error creating thread 1"); exit(EXIT_FAILURE); } if (pthread_create(&thread2, NULL, my_thread, (void *)&num2) != 0) { perror("Error creating thread 2"); exit(EXIT_FAILURE); } // 等待线程结束 pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; }
在这个示例中,我们创建了两个线程thread1
和thread2
,并分别传递了两个整数num1
和num2
作为参数。线程入口函数my_thread()
接收一个void *
类型的参数,我们将其转换为int *
类型,以便获取传递给线程的整数值。