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\n”, *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函数等待新线程结束执行。

阅读剩余
THE END