租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c++ pthread_create函数如何使用

发布时间:2023-10-31 14:50:24

c++ pthread_create函数如何使用

在C++中,你可使用pthread_create函数创建一个新的线程。该函数的声明以下:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

参数说明:

  • thread:指向pthread_t类型的指针,用于存储新创建的线程的ID。
  • attr:指向pthread_attr_t类型的指针,用于指定线程的属性。可以为NULL,表示使用默许属性。
  • start_routine:指向函数的指针,该函数是新线程要履行的函数。
  • arg:传递给start_routine函数的参数。

下面是一个简单的例子,演示怎样使用pthread_create函数创建一个新线程:

#include <pthread.h>
#include <iostream>

void* threadFunc(void* arg) {
    int value = *(int*)arg;
    std::cout << "Hello from thread! Value = " << value << std::endl;
    pthread_exit(NULL);
}

int main() {
    pthread_t thread;
    int value = 10;
    int result = pthread_create(&thread, NULL, threadFunc, &value);
    if (result != 0) {
        std::cout << "Failed to create thread." << std::endl;
        return 1;
    }
    pthread_join(thread, NULL); // 等待线程履行终了
    return 0;
}

在上面的例子中,我们定义了一个名为threadFunc的函数,作为新线程要履行的函数。在主函数中,我们首先创建了一个pthread_t类型的变量thread,用于存储新线程的ID。然后,我们创建一个整数变量value,并将其传递给pthread_create函数作为参数。最后,我们使用pthread_join函数等待新线程履行终了。

当运行上述程序时,你将会看到输出"Hello from thread! Value = 10"。这表明新线程成功地履行了threadFunc函数,并且能够访问传递给它的参数value。