c++ thread多线程示例代码
时间: 2023-09-01 14:07:15 浏览: 46
可以看下面这个示例代码:
```c++
#include <iostream>
#include <thread>
#include <chrono>
void sayHello() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
std::cout << "Starting main thread: " << std::this_thread::get_id() << std::endl;
std::thread t1(sayHello);
std::cout << "Thread " << t1.get_id() << " created" << std::endl;
t1.join(); // waits for t1 to finish
std::cout << "Exiting main thread" << std::endl;
return 0;
}
```
这个示例代码创建了一个 `std::thread` 对象,并在其上运行了一个 `sayHello()` 函数。主线程等待子线程执行完毕后才退出。
相关问题
C++多线程代码示例
以下是一个使用C语言编写的多线程代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
void *thread_function(void *arg)
{
int tid;
tid = *((int *)arg);
printf("Thread %d: Hello World!\n", tid);
pthread_exit(NULL);
}
int main()
{
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
int i;
// 创建多个线程
for (i = 0; i < NUM_THREADS; ++i)
{
thread_args[i] = i;
pthread_create(&threads[i], NULL, thread_function, (void *)&thread_args[i]);
}
// 等待线程执行完毕
for (i = 0; i < NUM_THREADS; ++i)
{
pthread_join(threads[i], NULL);
}
return 0;
}
```
该示例中,首先定义了一个线程执行函数`thread_function`,它接收一个`void*`类型的参数,并通过强制转换为`int*`类型来获取线程标识符。然后在函数中打印输出线程的标识符。
在`main`函数中,首先声明了一个存放线程对象的数组`threads`和存放线程参数的数组`thread_args`。然后使用`pthread_create`函数创建了多个线程,并将线程标识符存入`threads`数组中。每个线程的参数从`thread_args`数组中获取。接着使用`pthread_join`函数等待所有线程执行完毕。
c++thread多线程实例
当使用C++编程语言时,可以使用std::thread库来创建和管理多线程。以下是一个简单的C++多线程实例:
```cpp
#include <iostream>
#include <thread>
// 线程函数,打印线程ID
void printThreadID() {
std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
}
int main() {
// 创建两个线程
std::thread t1(printThreadID);
std::thread t2(printThreadID);
// 等待线程完成
t1.join();
t2.join();
return 0;
}
```
在上面的示例中,我们首先包含了`<iostream>`和`<thread>`头文件。然后定义了一个`printThreadID`函数,它会打印当前线程的ID。在`main`函数中,我们创建了两个线程`t1`和`t2`,它们都会执行`printThreadID`函数。最后,我们使用`join`函数等待这两个线程执行完成。
运行上述代码,您将看到类似以下输出:
```
Thread ID: 12345
Thread ID: 67890
```
这表明两个线程在不同的线程ID下并行执行。
请注意,多线程编程需要小心处理共享资源的同步和互斥问题,以避免数据竞争和其他并发问题。这里只是一个简单的多线程示例,实际应用中可能需要更复杂的同步机制来保证线程安全性。