int pthread_create(
pthread_t *thread,
const pthread_attr_t *attr,
void* (*start_routine)(void*),
void *arg)
创建一个新线程。
pthread_t
的定义如下:
typedef unsigned long int pthread_t;
pthread_t *thread
为线程ID
的指针
。
pthread_attr_t
的定义如下:
typedef struct __pthread_attr_s {
int __detachstate;
int __schedpolicy;
struct __sched_param __schedparam;
int __inheritsched;
int __scope;
size_t __guardsize;
int __stackaddr_set;
void *__stackaddr;
size_t __stacksize;
} pthread_attr_t;
const pthread_attr_t *attr
用来设置线程的属性,比如,指定线程优先级等,一般的情况下,我们没有必要修改。当其值为NULL
时,将使用默认属性。
void* (*start_routine)(void*)
是线程要运行的函数的指针
。
void *arg
是void* (*start_routine)(void*)
的实参。
若线程创建成功,则返回0
。
若线程创建失败,则返回错误码
, 并且*thread
并未赋予初始值。
#include<stdio.h>
#include<pthread.h>
/* 线程要执行的函数 */
void* run(void *args) {
printf("running start\n");
for(int i = 1; i <= 100; i++) {
printf("running %d\n", i);
}
printf("running end\n");
return NULL;
}
int main() {
pthread_t threadId;
int rc = pthread_create(&threadId, NULL, run, NULL);
if (0 == rc) {
printf("create thread success\n");
pthread_exit("wait to exit");
return 0;
} else {
printf("create thread fail!\n");
return 1;
}
}
使用cc命令编译:
cc -lpthread -o test_pthread test.c
注意:
main
函数的return
语句是退出进程,一旦执行到main
函数的return
语句,表示进程退出, 但是如果在return
语句之前调用了pthread_exit()函数
的话,如果还有其他进程在执行的话,就不会退出进程。