来段c++多线程代码
时间: 2023-02-07 12:23:11 浏览: 134
好的,这是一段简单的 C 语言多线程代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 线程的运行函数
void* thread_func(void* arg)
{
int* p = (int*) arg;
printf("子线程:参数为 %d\n", *p);
*p = 20;
return NULL;
}
int main(int argc, char* argv[])
{
pthread_t thread;
int arg = 10;
int* p_arg = &arg;
// 创建新线程
pthread_create(&thread, NULL, thread_func, p_arg);
// 等待子线程结束
pthread_join(thread, NULL);
printf("主线程:参数为 %d\n", arg);
return 0;
}
```
这段代码中创建了一个新的线程,并将一个整型变量作为参数传递给线程的运行函数。线程的运行函数输出了参数的值,然后将参数的值改为 20。主线程等待子线程结束后,输出参数的最终值。
运行结果如下:
```
子线程:参数为 10
主线程:参数为 20
```
希望这段代码能帮到你。
相关问题
生成一段c++多线程代码
以下是一个简单的多线程代码示例,它创建了两个线程并将它们运行在不同的核心上:
```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库,它创建了两个线程,并在不同的核心上运行它们。每个线程调用不同的函数,并输出一条消息。最后,它等待两个线程完成并退出。
c++写一段多线程代码
当然,请问您需要实现哪种多线程程序呢?可能需要一些具体的背景和需求来更好地编写代码。不过,下面提供一个简单的多线程代码示例:
```c
#include <pthread.h>
#include <stdio.h>
#define THREAD_NUM 3
void* thread_func(void* arg)
{
int* num = (int*) arg;
printf("Thread ID: %ld, Number: %d\n", pthread_self(), *num);
pthread_exit(NULL);
}
int main()
{
pthread_t threads[THREAD_NUM];
int nums[THREAD_NUM] = {1, 2, 3};
for (int i = 0; i < THREAD_NUM; i++) {
int ret = pthread_create(&threads[i], NULL, thread_func, (void*) &nums[i]);
if (ret) {
printf("Error: unable to create thread, return code: %d\n", ret);
return -1;
}
printf("Created thread #%d, ID: %ld\n", i, threads[i]);
}
pthread_exit(NULL);
}
```
该代码中,定义了一个 `thread_func()` 函数作为线程执行的函数体,其中通过 `pthread_self()` 获取当前线程 ID 和 `arg` 指针获取传递给线程的参数。然后,在 `main()` 函数中创建 `THREAD_NUM` 个线程,每个线程传递一个不同的整数参数给 `thread_func()` 函数,通过 `pthread_create()` 创建线程并保存了线程 ID。最后,等待所有线程执行完毕并释放资源,使用 `pthread_exit()` 实现。
请注意,线程编程需要特别注意线程安全和锁控制等问题。如果您需要更复杂的多线程程序,建议使用专业的线程库或框架来实现。