温馨提示×

c++ pthread_create函数怎么使用

c++
小亿
80
2023-10-31 14:50:24
栏目: 编程语言

在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。

0