温馨提示×

c语言怎么实现多线程

小亿
156
2023-11-15 23:33:36
栏目: 编程语言

在C语言中实现多线程可以使用POSIX线程库(pthread)或Windows线程库等。下面是一个使用POSIX线程库实现多线程的示例:

#include <stdio.h> #include <stdlib.h> #include <pthread.h> // 线程函数,传入一个整数参数 void* thread_func(void* arg) { int n = *(int*)arg; printf("Hello from thread %d\n", n); pthread_exit(NULL); } int main() { int num_threads = 5; pthread_t threads[num_threads]; int thread_args[num_threads]; // 创建多个线程 for (int i = 0; i < num_threads; i++) { thread_args[i] = i; pthread_create(&threads[i], NULL, thread_func, &thread_args[i]); } // 等待每个线程结束 for (int i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } printf("All threads are done.\n"); return 0; } 

在这个示例中,thread_func是一个线程函数,用来打印线程的标识号。main函数中首先创建了多个线程,每个线程都传入一个整数参数,然后等待每个线程执行完毕。最后输出所有线程结束的提示信息。

要编译上述代码,可以使用以下命令:

gcc -o multithreading multithreading.c -lpthread 

这将生成一个可执行文件multithreading,运行它将会看到多个线程按顺序打印出它们的标识号,最后输出所有线程结束的提示信息。

请注意,在使用多线程时要注意线程间的同步和互斥问题,以避免竞争条件和数据访问冲突等问题。

0