int pthread_create (pthread_t tid, const pthread_attr_t* attr, void *(*start_fun)(void), void* arg);
创建线程函数:
tid : 创建线程成功后的线程ID。
attr: 线程的一些配置,用于指定各种线程的属性。
start_fun: 线程创建以后从这个函数开始执行。
arg : start_fun 的参数。
返回值 : 0为创建成功。
和 fork后父子进程的运行先后顺序未知是一样的,主线程创建了子线程,运行顺序同样未知。
1 #include <pthread.h>
2 #include <stdio.h>
3 #include <unistd.h>
4
5 void printids(const char* s){
6 pid_t pid;
7 pthread_t tid;
8
9 pid = getpid();
10 tid = pthread_self();
11 printf("%s pid:%u tid:%u\n", s, (unsigned int)pid, (unsigned int)tid);
12 }
13
14
15 void* pthread_run(void *arg){
16 printids("new thread");
17 return ((void *)0);
18 }
19 int main(){
20
21 pthread_t tid;
22 if(pthread_create(&tid, NULL, pthread_run, NULL)){
23 printf("error");
24 return 0;
25 }
26 sleep(1);
27 printids("main thread");
28 return 0;
29 }
30
运行结果:
new thread pid:4345 tid:3175823632
main thread pid:4345 tid:3191752464