前面的一篇,介绍了进程和线程的关系,以及创建了一个简单的单线程的程序。我们下面通过主线程中使用pthread_create系统调用创建一个或多个子线程。
int pthread_create(
pthread_t *thread, //线程ID
const pthread_attr_t *attr, //线程属性
void *(*start_routine) (void *), //回调函数
void *arg //回调函数的参数
);
- 线程ID:线程的唯一标识符,新创建的线程会将将id填充到thread指针的内存
- 线程属性:调度策略/继承/分离(这里暂时不用理会,调用时候,传入参数NULL表示会使用默认的属性)
- 回调函数的指针:当前线程栈通过传入函数指针调用被调用函数的主体
- 回调函数的参数,由于该系统调用本身只有一个参数,因此如果需要向回调参数传递多个参数的话,请使用struct封装多个参数。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void display_id(char* s){
pid_t pid;
pthread_t tid;
pid=getpid();
tid=pthread_self();
printf("%s 进程: %u, 线程ID 0x%lx\n",s,pid,tid);
}
void *thread_func(void* args){
display_id(args);
return (void*)0;
}
int main(){
pthread_t ntid;
int err;
err=pthread_create(&ntid,NULL,thread_func,"子线程");
if(err!=0){
printf("创建线程失败\n");
return 0;
}
display_id("主线程:");
sleep(3);
return 0;
}

小结
本篇介绍了如何通过pthread_create系统调用,在主线程中创建出一个子线程。并且分别打印各个线程中的进程ID和线程ID,我们知道,一个进程中的多个线程共享同一个进程的资源
网友评论