c语言如何实现多线程
时间: 2023-10-19 08:09:54 浏览: 49
在 C 语言中,可以使用 POSIX 线程库(Pthreads)来实现多线程。下面是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 线程函数
void *thread_func(void *arg)
{
int i;
for (i = 0; i < 5; i++) {
printf("Thread %d running\n", *(int *)arg);
}
pthread_exit(NULL);
}
int main()
{
pthread_t threads[3];
int thread_args[3] = {1, 2, 3};
int i;
// 创建三个线程
for (i = 0; i < 3; i++) {
if (pthread_create(&threads[i], NULL, thread_func, &thread_args[i])) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
// 等待线程结束
for (i = 0; i < 3; i++) {
if (pthread_join(threads[i], NULL)) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
}
return 0;
}
```
上述代码中,`pthread_create` 函数用于创建线程,接受四个参数:第一个参数为指向线程标识符的指针,第二个参数用于设置线程的属性,第三个参数为线程函数,最后一个参数为传递给线程函数的参数。`pthread_join` 函数用于等待线程结束并回收资源。
需要注意的是,在多线程编程中,需要注意线程同步和互斥,以避免出现竞态条件和死锁等问题。