租用问题

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

< 返回租用问题列表

Unix中pthread_create的用法是什么

发布时间:2023-12-15 01:19:43

Unix中pthread_create的用法是甚么

在Unix系统中,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函数的参数。

返回值:

  • 成功:返回0,表示线程创建成功。
  • 失败:返回一个非零毛病代码,表示线程创建失败。

使用pthread_create函数时,需要提供一个线程函数作为start_routine的实现,该函数的原型以下:

void* thread_func(void* arg);

其中,arg参数为传递给线程函数的参数。线程函数履行完后,可以通过返回一个指针来传递结果给主线程。可使用pthread_exit函数来终止线程的履行。

示例代码以下:

#include <stdio.h> #include <pthread.h>

void* thread_func(void* arg) { int* num = (int*)arg; printf(“Thread: %d ”, *num); pthread_exit(NULL); }

int main() { pthread_t thread_id; int num = 10;

pthread_create(&thread_id, NULL, thread_func, &num);

// 等待新线程结束
pthread_join(thread_id, NULL);

return 0;

}

本示例中,创建了一个新线程,新线程履行thread_func函数,并传递了一个整数参数。在thread_func函数中,将参数强迫转换为整数指针,并打印出来。主线程使用pthread_join函数等待新线程结束履行。