温馨提示×

linux中的pthread_create函数怎么使用

小亿
85
2023-12-21 17:53:38
栏目: 编程语言

在Linux中,`pthread_create()`函数用于创建一个新的线程。它的原型如下:

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

下面是对各个参数的解释:

`thread`:指向线程标识符的指针,用于存储新线程的ID。

`attr`:线程的属性,通常使用默认值`NULL`。

`start_routine`:线程执行的函数入口点,该函数不能带有任何参数或返回值。

`arg`:传递给线程函数的参数。

要使用`pthread_create()`函数,你需要包含头文件`pthread.h`。然后,你可以在程序中调用该函数来创建新的线程。

下面是一个简单的例子演示如何使用`pthread_create()`函数来创建一个新的线程:

#include 
#include 
#include 
// 线程执行的函数
void *print_message(void *message) {
    char *msg = (char *)message;
    printf("%s\n", msg);
    pthread_exit(NULL);
}
int main() {
    pthread_t thread;
    char *message = "Hello, world!";
    // 创建新线程并传递参数
    int result = pthread_create(&thread, NULL, print_message, (void *)message);
    if (result != 0) {
        fprintf(stderr, "Error creating thread.\n");
        exit(EXIT_FAILURE);
    }
    // 主线程继续执行其他任务
    printf("Main thread executing.\n");
    // 等待子线程结束
    pthread_join(thread, NULL);
    return 0;
}

在上面的例子中,我们首先定义了一个函数 `print_message()`,它作为新线程执行的入口点。然后,在主函数中,我们调用 `pthread_create()` 函数来创建新线程,并传递参数 `message` 给新线程。最后,我们使用 `pthread_join()` 函数等待新线程执行结束。

这只是一个简单的示例,`pthread_create()` 函数还有其他更复杂的用法和功能。你可以查阅相关文档以获取更多详细信息。

0