c++ pthread
时间: 2023-11-25 12:08:43 浏览: 40
好的,我明白了。您的问题是:
如何在 C++ 中使用 pthread 库?
在 C++ 中使用 pthread 库需要包含头文件 `<pthread.h>`,并且需要链接 `-pthread` 选项。下面是一个简单的例子:
```c++
#include <iostream>
#include <pthread.h>
void* thread_func(void* arg) {
std::cout << "Hello from thread!" << std::endl;
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);
pthread_join(thread, NULL);
return 0;
}
```
在上面的例子中,我们创建了一个线程并在其中打印一条消息。`pthread_create` 函数用于创建线程,它接受四个参数:线程标识符、线程属性、线程函数和函数参数。`pthread_join` 函数用于等待线程结束。
相关问题
C++ pthread_create
pthread_create是C++中用于创建线程的函数。它是POSIX线程库的一部分,用于在多线程环境下创建新的线程。
pthread_create函数的原型如下:
```c++
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
```
参数说明:
- thread:指向pthread_t类型的指针,用于存储新创建线程的标识符。
- attr:指向pthread_attr_t类型的指针,用于设置线程的属性。可以传入NULL,表示使用默认属性。
- start_routine:指向函数指针,该函数是新线程要执行的函数。函数的返回类型必须为void*,参数类型为void*。
- arg:传递给start_routine函数的参数。
调用pthread_create函数后,会创建一个新的线程,并开始执行start_routine函数。start_routine函数可以是全局函数、静态成员函数或Lambda表达式等。
以下是一个简单的示例代码:
```c++
#include <iostream>
#include <pthread.h>
void* threadFunc(void* arg) {
int* num = static_cast<int*>(arg);
std::cout << "Thread number: " << *num << std::endl;
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int num = 10;
int ret = pthread_create(&thread, NULL, threadFunc, &num);
if (ret != 0) {
std::cerr << "Failed to create thread" << std::endl;
return 1;
}
pthread_join(thread, NULL);
return 0;
}
```
C++ pthread_join
`pthread_join`函数用于等待指定的线程终止,并获取线程的返回值。它的函数原型如下:
```c++
int pthread_join(pthread_t thread, void **retval);
```
其中,`thread`参数是要等待的线程的标识符,`retval`参数是一个指向指针的指针,用于存储线程的返回值。
下面是一个使用`pthread_join`函数的示例:
```c++
#include <iostream>
#include <pthread.h>
void* threadFunc(void* arg) {
int* value = new int(42);
return value;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, threadFunc, NULL);
void* returnValue;
pthread_join(thread, &returnValue);
int* value = static_cast<int*>(returnValue);
std::cout << "Thread returned: " << *value << std::endl;
delete value;
return 0;
}
```
在上面的示例中,我们创建了一个线程`thread`,并在`threadFunc`函数中返回了一个动态分配的整数值。然后,我们使用`pthread_join`函数等待线程终止,并获取线程的返回值。最后,我们将返回值转换为整数类型并输出。