linux c 多线程
时间: 2023-07-03 18:10:28 浏览: 47
Linux C 多线程可以使用 POSIX 线程库(pthread)实现。以下是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_func(void *arg) {
int tid = *(int*)arg;
printf("Thread %d is running\n", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int tids[5];
for (int i = 0; i < 5; i++) {
tids[i] = i;
pthread_create(&threads[i], NULL, thread_func, &tids[i]);
}
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
printf("All threads have finished\n");
return 0;
}
```
上述代码创建了 5 个线程,每个线程都会输出自己的线程 ID。在主线程中,使用 pthread_join 函数等待所有线程执行完成后再输出一条信息。
需要注意的是,在使用 pthread_create 函数创建线程时,需要传入线程函数的指针和参数。在本例中,线程函数为 thread_func,参数为线程 ID。由于 pthread_create 函数的参数类型为 void*,因此需要将参数转换为指向 int 类型的指针。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)