C++库使用pthread_create
时间: 2023-12-27 21:25:39 浏览: 27
C++库中的pthread_create函数用于创建一个新的线程。它的原型如下:
```c++
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
```
其中,`thread`是指向线程标识符的指针,`attr`是指向线程属性的指针,`start_routine`是指向线程函数的指针,`arg`是传递给线程函数的参数。
下面是一个使用pthread_create函数创建线程的示例代码:
```c++
#include <iostream>
#include <pthread.h>
void* threadFunc(void* arg) {
int threadId = *(int*)arg;
std::cout << "Hello from thread " << threadId << std::endl;
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int threadId = 1;
int ret = pthread_create(&thread, NULL, threadFunc, &threadId);
if (ret != 0) {
std::cerr << "Failed to create thread" << std::endl;
return 1;
}
pthread_join(thread, NULL);
return 0;
}
```
在上面的示例中,我们定义了一个线程函数`threadFunc`,它接受一个整数参数作为线程ID,并在控制台输出"Hello from thread "加上线程ID。然后,在主函数中,我们创建了一个线程,并将线程ID作为参数传递给线程函数。最后,我们使用pthread_join函数等待线程结束。