帮我用c写一个多线程模板
时间: 2023-08-02 07:40:01 浏览: 47
好的,以下是一个基本的多线程模板,供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
void *thread_func(void *thread_id) {
long tid;
tid = (long) thread_id;
printf("Thread %ld is running\n", tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
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, thread_func, (void *) t);
if (rc) {
printf("Error: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
```
这个模板创建了 `NUM_THREADS` 个线程,并且每个线程都运行 `thread_func()` 函数。在 `thread_func()` 函数中,线程会打印出自己的 ID,然后退出。在主函数中,我们使用 `pthread_create()` 函数创建线程,并且使用 `pthread_exit()` 函数来等待所有线程结束。
当然,这只是一个基本的模板,具体的多线程应用还需要根据实际情况进行修改和优化。