C++ pthread_create demo
时间: 2023-07-06 09:40:47 浏览: 55
下面是一个使用 `pthread_create` 创建线程的 C++ 示例代码:
```c++
#include <iostream>
#include <pthread.h>
using namespace std;
void* thread_func(void* arg)
{
int* p = (int*)arg;
cout << "Thread ID: " << pthread_self() << ", Arg: " << *p << endl;
return NULL;
}
int main()
{
pthread_t tid;
int arg = 12345;
// 创建线程
if (pthread_create(&tid, NULL, thread_func, &arg) != 0) {
cout << "Error: Failed to create thread." << endl;
return -1;
}
// 等待线程结束
if (pthread_join(tid, NULL) != 0) {
cout << "Error: Failed to join thread." << endl;
return -1;
}
cout << "Main thread exit." << endl;
return 0;
}
```
在上面的示例代码中,我们首先定义了一个名为 `thread_func` 的函数,这个函数将作为线程的入口函数。在 `thread_func` 函数中,我们打印了当前线程的 ID 和传入的参数值,然后返回 NULL。
在主函数中,我们首先定义了一个 `pthread_t` 类型的变量 `tid`,用于存储线程 ID。然后定义了一个整型变量 `arg`,用于向线程传递参数。接着,我们使用 `pthread_create` 函数创建了一个新线程,并将线程 ID 存储在 `tid` 变量中。在调用 `pthread_create` 函数时,我们传入了四个参数:
- 第一个参数是指向线程 ID 变量的指针。
- 第二个参数是线程属性,我们将其设置为 NULL。
- 第三个参数是指向线程入口函数的指针,即 `thread_func` 函数。
- 第四个参数是传递给线程入口函数的参数,即 `arg` 变量的地址。
接下来,我们使用 `pthread_join` 函数等待线程结束。在调用 `pthread_join` 函数时,我们传入了两个参数:
- 第一个参数是要等待的线程 ID。
- 第二个参数是指向线程返回值的指针,我们将其设置为 NULL,表示不关心线程的返回值。
最后,我们在主函数中打印了一条消息,表示主线程退出。