c++ 多线程的例子
时间: 2023-09-18 16:07:25 浏览: 51
多线程是指在一个程序中同时运行多个线程,每个线程都独立执行不同的任务。下面是一个简单的多线程的例子,使用C语言的pthread库实现:
```c
#include <stdio.h>
#include <pthread.h>
// 线程函数
void *thread_func(void *arg) {
int thread_id = *(int *)arg;
printf("Thread %d is running\n", thread_id);
// 执行一些任务
printf("Thread %d finished\n", thread_id);
return NULL;
}
int main() {
pthread_t threads[3];
int thread_ids[3] = {1, 2, 3};
// 创建三个线程
for (int i = 0; i < 3; i++) {
if (pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]) != 0) {
fprintf(stderr, "Failed to create thread %d\n", i+1);
return 1;
}
}
// 等待每个线程结束
for (int i = 0; i < 3; i++) {
if (pthread_join(threads[i], NULL) != 0) {
fprintf(stderr, "Failed to join thread %d\n", i+1);
return 1;
}
}
printf("All threads finished\n");
return 0;
}
```
这个例子创建了三个线程,每个线程打印出自己的编号并执行一些任务。主线程使用pthread_create函数创建线程,传入线程函数和参数。然后,使用pthread_join函数等待每个线程结束。最后,主线程打印出所有线程都完成的消息。注意,这只是一个简单的示例,实际使用中可能需要更复杂的线程同步和互斥机制来避免竞态条件和死锁等问题。