生成一段c++多线程代码
时间: 2023-10-24 17:07:57 浏览: 55
以下是一个简单的多线程代码示例,它创建了两个线程并将它们运行在不同的核心上:
```c
#include <stdio.h>
#include <pthread.h>
void *thread1_func(void *arg) {
printf("Thread 1 is running\n");
return NULL;
}
void *thread2_func(void *arg) {
printf("Thread 2 is running\n");
return NULL;
}
int main() {
pthread_t thread1, thread2;
// 创建线程1
if (pthread_create(&thread1, NULL, thread1_func, NULL)) {
printf("Error creating thread 1\n");
return 1;
}
// 创建线程2
if (pthread_create(&thread2, NULL, thread2_func, NULL)) {
printf("Error creating thread 2\n");
return 1;
}
// 等待线程1和线程2结束
if (pthread_join(thread1, NULL)) {
printf("Error joining thread 1\n");
return 1;
}
if (pthread_join(thread2, NULL)) {
printf("Error joining thread 2\n");
return 1;
}
return 0;
}
```
该程序使用了pthread库,它创建了两个线程,并在不同的核心上运行它们。每个线程调用不同的函数,并输出一条消息。最后,它等待两个线程完成并退出。