温馨提示×

Linux的pthread_create怎么使用

小亿
92
2023-08-01 16:30:24
栏目: 编程语言

pthread_create函数可以用来创建一个新的线程。它的原型如下:

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

参数说明:

  • thread:用于存储新线程标识符的变量指针。

  • attr:用于指定新线程的属性,通常使用默认属性,可以传入NULL。

  • start_routine:新线程将要执行的函数的指针。

  • arg:传递给新线程的参数。

下面是一个使用pthread_create函数创建新线程的示例代码:

#include <stdio.h>
#include <pthread.h>
void* thread_function(void* arg) {
printf("Hello from the new thread!\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, NULL, thread_function, NULL);
if (result != 0) {
printf("Error creating thread: %d\n", result);
return 1;
}
printf("Hello from the main thread!\n");
pthread_join(thread, NULL); // 等待新线程执行完毕
return 0;
}

在上面的代码中,我们定义了一个新线程函数thread_function,它打印一条消息,然后调用pthread_exit来退出线程。在主函数中,我们通过调用pthread_create函数来创建新线程,并传入新线程函数的指针。然后,我们在主线程中打印另一条消息,并调用pthread_join函数来等待新线程执行完毕。

注意:在使用pthread_create函数创建新线程时,需要在编译时链接pthread库,可以使用-pthread选项来编译,例如:

gcc -pthread main.c -o main

0